J
Johnny Drama
Let's say I have an interface IScope:
internal interface IScope{}
....and I have a class that implements IScope:
internal class Scope:IScope{}
.... and I have a method that returns List<Scope>:
public List<Scope> GetScopes(){return new List<Scope>();}
.... and I'd like to pass the return value from the above method to another
method that takes a List<IScope>, say a method that looks like:
public void ProcessScopes(List<IScope> scopes){}
.... I figured that a List<Scope> could be directly converted to List<IScope>
since Scope derives from IScope, but apparently I was wrong. The conversion
doesn't work, even with an explicit cast. Could someone explain the
rationale for *why* it doesn't work? My first attempt at a workaround for
this was to build the following conversion method -- something like:
public static List<U> UpcastList<U,D>(List<D> lstD) where D:U{
List<U> lstU=new List<U>();
foreach(D d in lstD){
lstU.Add(d);
}
return lstU;
}
..this seems to work for me, but I'm still perplexed as to why the
direct conversion above fails at compile time. Any comments would be
appreciated.
Thanks..
internal interface IScope{}
....and I have a class that implements IScope:
internal class Scope:IScope{}
.... and I have a method that returns List<Scope>:
public List<Scope> GetScopes(){return new List<Scope>();}
.... and I'd like to pass the return value from the above method to another
method that takes a List<IScope>, say a method that looks like:
public void ProcessScopes(List<IScope> scopes){}
.... I figured that a List<Scope> could be directly converted to List<IScope>
since Scope derives from IScope, but apparently I was wrong. The conversion
doesn't work, even with an explicit cast. Could someone explain the
rationale for *why* it doesn't work? My first attempt at a workaround for
this was to build the following conversion method -- something like:
public static List<U> UpcastList<U,D>(List<D> lstD) where D:U{
List<U> lstU=new List<U>();
foreach(D d in lstD){
lstU.Add(d);
}
return lstU;
}
..this seems to work for me, but I'm still perplexed as to why the
direct conversion above fails at compile time. Any comments would be
appreciated.
Thanks..