Cast list of interface to list of objects

cast list of interface to list of class java
c# list of interface objects
c# return list of interface
how to add class object to list in c#
c# cast interface to class
c# cast interface to derived type
get value from list object in c#
list of interfaces

I have a method that returns List<ThisInterface>. I would expect that I would be able to cast the results of that method to List<ThisClass>, as long as ThisClass implements ThisInterface. However, I receive the following error trying to do so:

Unable to cast object of type System.Collections.Generic.List'1[IThisInterface] to type System.Collections.Generic.List’1[ThisClass].

Any thoughts? Do I need to write a constructor for this?

If you have a List<IThisInterface>, then you cannot cast that list object to List<ThisClass>. Even if all the items inside of the list are ThisClass objects, the list is still a list of IThisInterface objects.

What you need to do is create a new List<ThisClass> list and then populate that with all the items of the original list but cast those to ThisClass first.

Fortunately, that is exactly what the LINQ method Enumerable.Cast<T> does:

List<IThisInterface> list = GetData();

// cast the list to a `ThisClass` list
List<ThisClass> newList = list.Cast<ThisClass>().ToList();

How do i convert a List<Interface> to List<Class> in c#, Using Cast<> will fail if any of the objects implements IReaderInfo a list of interfaces it means it can return any object that implements the  For example, methods typically return interfaces when they do intend to return different types, eg mock objects, or handle multiple implementations. By returning List<ReaderInfo> you prevent your method from handling valid objects

I'm afraid your expectation is incorrect. A List<IThisInterface> is allowed to contain elements of any type that implements IThisInterface. If you were allowed to cast this to List<ThisClass>, the cast would add a restriction - suddenly only a specific implementation of the interface would be allowed in the list, and for example when you get an item from the list you would be allowed to assume it is of type ThisClass - which it may or may not be since what you were given was a less restrictive list.

https://social.msdn.microsoft.com/Forums/vstudio/e, Represents a strongly typed list of objects that can be accessed by index. interface, then the equality comparer is the Equals(T) method of that interface; otherwise, the default equality comparer is Object. Cast<TResult>(IEnumerable​). Oh. I think I need to learn how to read. I thought the original answer said that the objects in the list would be deep copied and recreated which didn't make sense to me. But I clearly missed the part where only a new list is created with the same objects. – Robert Noack Dec 23 '14 at 20:06

No (by way of example)

IAnimal animal = new Giraffe(); // Giraffe is an IAnimal so OK.
Lion lion = (Lion)animal; // should this work? Lion is an IAnimal???

Update:

For some it must be stated that Giraffe and Lion both implement an interface called IAnimal and that Giraffe is not a subclass of Lion. Others managed to understand that IThisInterface is akin to IAnimal and ThisClass is akin to Lion with a rhetorical "should this work".

The answer is self evidently no. A Lion is a concretion of IAnimal, but it does not follow that having an instance of IAnimal means that you have a Lion. Such a cast will throw but is also obviously wrong and so neatly illustrates the problem. In the same way, ThisClass implementing IThisInterface means that ThisClass is a concretion of IThisInterface, but just because you find yourself in possession of a collection of IThisInterface's, does not mean that you can assume that such is a list of ThisClass's. It might be, but equally it might be any other object that implements IThisInterface.

Anyway, if you search for covariance and contravariance you will find a number of similar questions that will let you understand further.

List<T>, Description: A cast from an abstract collection to a concrete Normally, except when constructing an object, it is better to use the abstract types because this The List interface does not provide a poll method, so the original  Problem is in add to list. When i Add first element with point`s (2,2)m second (3,3) then first change value to second element on the list, when i add thirth with points (5,6) then first and secont element change value to thirth element and list look like: list[0] - Begin point - 5 - EndPoint - 6 list[1] - Begin point - 5 - EndPoint - 6

Cast from abstract to concrete collection - Java queries, Interface declaration lists all methods (and their signatures) that the interface type When casting object types you agree to that risk of causing an exception  The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface by using an array whose size is dynamically increased as required. You can add items to a List<T> by using the Add or AddRange methods. The List<T> class uses both an equality comparer and an ordering comparer.

Interfaces and Polymorphism, Creating List Objects: List is an interface, and the instances of List can be created by implementing various classes in the following ways: List a = new ArrayList();  Say you wanted to take a List<BaseClass> and only want to really get a List<Derived1> from it. There are some options here. There are some options here. You can loop over all the object in the given list and create another list of just Derived1, in each iteration checking if the current object is Dervied1 and adding it to the return list.

List Interface in Java with Examples, m_attachObjectDataListToProcess = new List<idata>(); Then you can add AttachToObjectData objects to m_attachObjectDataListToProcess as  Casting and type conversions (C# Programming Guide) 07/20/2015; 5 minutes to read +8; In this article. Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable's type.

Comments
  • Where is the code where you are casting?
  • Why are you casting? You should be able to access the methods on the interface
  • Makes perfect sense. Thank you.
  • I just tested this solution out and it worked like a charm. Many thanks to you, @poke.
  • @christok Worth mentioning that this will throw an exception if any of the items are not ThisClass, instead you could use list.OfType<ThisClass>().ToList(). Of course, this also begs the question of why you want to cast them in the first place? There's a reason you have the interfaces...
  • This totally makes sense. Thanks!
  • This answer is missing a few things for it to be instructive, such as a definition for IAnimal, Giraffe, and Lion. Also, it's missing a variable name in the Lion assignment. And it doesn't mention which exception is thrown (or even if one is thrown), nor does it say why this doesn't work.