c# - Cast between List<MyType> and List<IMyType> -


i'm trying work around lack of support return type covariance in c# described in this question , first 2 answers it. part i'm not having problems setting casts, 1 property i'm using list of objects/interfaces stymieing efforts.

what need in order make casts ifoo.manybars work?

public interface ibar { }  public interface ifoo {     ibar abar { get; set; }     ienumerable<ibar> manybars { get; set; } }  class cbar : ibar { }  class cfoo : ifoo {     public cbar abar { get; set; }       //this cast works     ibar ifoo.abar      {         { return abar; }         set { abar = (cbar)value; }     }      public list<cbar> manybars { get; set; }      //the compiler can't cast either of these     list<ibar> ifoo.manybars     {         { return (list<ibar>)manybars; }         set { manybars = (list<cbar>)value; }     } } 

try this. have add using system.linq; top of source file, if it's not there already.

list<ibar> ifoo.manybars {     { return manybars.cast<ibar>().tolist(); }     set { manybars = value.cast<cbar>().tolist(); } } 

note allocate , copy new array on each access property. if not want, should consider alternative approach, such exposing property using type ienumerable<ibar>.

using list<ibar> means might try anobject.manybars.remove(0) absolutely nothing list stored in anobject, since copy returned.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -