40339

Cast in List object

Question:

I have an interface A, class B inherits from interface A. I have a list of objects:

List<B> myB; List<A> myA;

I want to assign myB to myA but I get a error "Cannot implicit convert type 'B' to 'A':

myA = myB;

Please help me. Thanks.

Answer1:

You need to convert each element of the list. It cannot be automatically converted for you. Easiest would be Linq:

myA = myB.Cast<A>().ToList();

<strong>Update</strong>: This question: <a href="https://stackoverflow.com/questions/833447/why-is-this-cast-not-possible" rel="nofollow">Why is this cast not possible?</a> discusses it in more detail.

Answer2:

It might help you: <a href="https://stackoverflow.com/questions/44942/cast-listint-to-liststring" rel="nofollow">Cast List<int> to List<string> in .NET 2.0</a>

Answer3:

IList<T> is not covariant, where as IEnumerable<T> is, you can do the following..

void Main() { IEnumerable<B> myB= new List<B>(); IEnumerable<A> myA = myB; } public interface A { } public class B :A { }

see this <a href="https://stackoverflow.com/questions/4034495/question-about-c-covariance" rel="nofollow">previous SO Question</a>

Answer4:

You need to make a way to convert between type A and type B.

There is no way to assign a list of one type to another, unless the type B is the same as type A.

You can use the Cast<T> operator for derived types:

class A {} class AA : A {} List<AA> aas = new List<AA> {new AA()}; List<A> bunchofA = aas.Cast<A>().ToList();

This only works when casting to less derived types (from descendant to ancestor). This won't work:

List<A> bunchofA = new List<A> {new A()}; List<AA> aas = bunchofA.Cast<AA>.ToList();

Because the compiler cannot know what to do to make the extra bits that AA has from A.

You can also, in a rather contrived way, use implicit conversion:

class A { } class B { public static implicit operator B(A a) { return new B(); } public static implicit operator A(B a) { return new A(); } } List<B> bs = new List<B>{new B()}; List<A> bunchOfA = bs.Select(b => (A)b).ToList();

This will work in either direction, but might cause confusion, so it is better to create explicit conversion methods and use those.

Answer5:

That is correct. List is a list of Apples and List is a list of .. err .. batmans! You cannot try to put one into the other.

Technically, you cannot refer to one as the other!

Recommend

  • DSPACK example for converting audio sample rate on the fly?
  • SWT: FontDialog without color selector
  • Are there any fluent WPF projects? [closed]
  • ObjectMaterialize in EF not firing on first level query
  • UIimage to char* conversion
  • When querying against a view, a filtering clause in the view's definition is being ignored
  • Finding All Combinations (cartesian product) of list values in vb.net
  • Easiest way to covert part of a byte array to uint16
  • Cannot convert a char value to money. The char value has incorrect syntax
  • Can you render a page with multiple forms instead of one form for a jQuery, Rails 3 update?
  • How to bind comma separated list of values to List
  • MySql - get days remaining
  • VB.NET: How do I use coalesce with db column values and nullable types? Or is there a better solutio
  • Jooq casting String to BigDecimal
  • Is it mandatory to have a doGet or doPost method?
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • Stitching 2 images (OpenCV)
  • How to set current CultureUI via XAML binding
  • RavenDB indexing errors
  • Many to Many in Linq using Dapper
  • Multiple Left Join LINQ-to-entities
  • Where these are stored?
  • Trying to string.Join an IList
  • Suqueries in select clause with JPA
  • Exception creating JSON with LINQ
  • NHibernate manually control fetching
  • Application level floating views with navigation in Android
  • Cannot get the UserManager class
  • Default parameter as generic type
  • Linq Merge lists
  • Do I need to seed any random number generator before using EVP_PKEY_keygen of OpenSSL?
  • Set the selected item in dropdownlist in MVC3
  • Ajax Loaded meta Tags
  • Xamarin Forms - UWP Fonts
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Arrays break string types in Julia
  • retrieve vertices with no linked edge in arangodb
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Understanding cpu registers
  • Add sale price programmatically to product variations