Home >Backend Development >C++ >How to Convert a List to a List in .NET?
Transforming List
This guide explains how to convert a list of Client
objects (List<Client>
) into a list of their corresponding IDic
interfaces (List<IDic>
).
Why Direct Casting Fails
Direct casting from a derived type (like Client
) to a base type (IDic
) is permitted in .NET. However, the reverse is not straightforward due to covariance limitations. These restrictions prevent unsafe operations where a base-type list could unexpectedly contain derived-type elements, preserving type safety.
Effective Conversion Methods
Two reliable methods achieve the desired conversion:
1. Leveraging IEnumerable<IDic>
( .NET 4 and later)
.NET 4 and later versions support covariance with IEnumerable<T>
. This enables conversion from List<Client>
to IEnumerable<IDic>
, allowing iteration over Client
objects as IDic
instances.
2. Constructing a New List
To create a List<IDic>
, you must explicitly build a new list and populate it with the interface references. .NET 4 offers the ToList<T>()
method for this. .NET 3.5 utilizes Cast<T>()
followed by ToList()
.
Important Note on Data Independence
Both techniques generate separate lists, maintaining type safety. Crucially, modifications to the original List<Client>
will not automatically update the new List<IDic>
. Only changes directly made to the Client
objects themselves will be visible in both lists.
The above is the detailed content of How to Convert a List to a List in .NET?. For more information, please follow other related articles on the PHP Chinese website!