public interface IDic
{
int Id { get; set; }
string Name { get; set; }
}
public class Client : IDic
{
}
How can I cast List<Client>
to List<IDic>
?
public interface IDic
{
int Id { get; set; }
string Name { get; set; }
}
public class Client : IDic
{
}
How can I cast List<Client>
to List<IDic>
?
In .Net 3.5, you can do the following:
The constructor for List in this case takes an IEnumerable.
list though is only convertible to IEnumerable. Even though myObj may be convertible to ISomeInterface the type IEnumerable is not convertible to IEnumerable.
Its only possible by creating new
List<IDic>
and transfering all elements.I too had this problem and after reading Jon Skeet's answer I modified my code from using
List<T>
to useIEnumerable<T>
. Although this does not answer the OP's original question of How can I castList<Client>
toList<IDic>
, it does avoid the need to do so and thus may be helpful to others who encounter this issue. This of course assumes that the code that requires the use ofList<IDic>
is under your control.E.g.:
Instead of:
A Cast iterator and .ToList():
List<IDic> casted = input.Cast<IDic>().ToList()
will do the trick.Originally I said covariance would work - but as Jon has rightly pointed out; no it won't!
And originally I also stupidly left off the
ToList()
callYou can't cast it (preserving reference identity) - that would be unsafe. For example:
Now you can convert a
List<Apple>
to anIEnumerable<IFruit>
in .NET 4 / C# 4 due to covariance, but if you want aList<IFruit>
you'd have to create a new list. For example:But this is not the same as casting the original list - because now there are two separate lists. This is safe, but you need to understand that changes made to one list won't be seen in the other list. (Modifications to the objects that the lists refer to will be seen, of course.)