Home >Backend Development >C++ >How Can I Convert a List of Derived Classes to a List of Base Classes in C#?
Converting a List of Derived Classes to a List of Base Classes in C#
Inheritance in C# allows creating derived classes from base classes or interfaces. However, directly assigning a List
of a derived class to a List
of its base class isn't permitted. This limitation arises from the type system's strictness regarding generic type parameters.
Consider this example:
<code class="language-csharp">interface IA {} class B : IA {} class C : B {} class Test { static void Main(string[] args) { IA a = new C(); // This is valid List<IA> listOfIA = new List<C>(); // Compiler error } }</code>
To overcome this, we can employ two primary methods:
Method 1: Using ConvertAll
This approach iterates through the list of derived classes and explicitly casts each element to the base class type.
<code class="language-csharp">List<C> listOfC = new List<C>(); // Your list of derived classes List<IA> listOfIA = listOfC.ConvertAll(x => (IA)x);</code>
Method 2: Using LINQ's Cast
LINQ provides a more concise solution using the Cast<T>
method. This method performs the same type conversion as ConvertAll
but with a more streamlined syntax.
<code class="language-csharp">List<C> listOfC = new List<C>(); // Your list of derived classes List<IA> listOfIA = listOfC.Cast<IA>().ToList();</code>
Both methods achieve the same result: a new list containing the objects from the original list, but with the base class type. The LINQ approach (Cast<T>
) is generally preferred for its readability and conciseness. Remember to handle potential exceptions if the cast might fail (e.g., if the list contains elements that aren't actually derived from the base class).
The above is the detailed content of How Can I Convert a List of Derived Classes to a List of Base Classes in C#?. For more information, please follow other related articles on the PHP Chinese website!