Home >Backend Development >C++ >Why Can't I Assign List to List in C# 2.0?

Why Can't I Assign List to List in C# 2.0?

Linda Hamilton
Linda HamiltonOriginal
2025-02-02 05:21:09668browse

Why Can't I Assign List to List in C# 2.0?

C# 2.0 The generic list of generics: List & lt; derived class & gt; cannot directly assign a value to list & lt; base class & gt;

C#variance characteristic refers to the ability to participate in collaborative or inverted value. However, trying List & LT; derived category & gt; assigned to List & LT; base class & gt;

Even if it is explicitly transformed, it will fail, which highlights the problem. It should be clear that this is not a problem of coordination. In fact, in order to ensure the security of the compilation, this assignment is clearly prohibited.
<code class="language-csharp">List<动物> animalsList = new List<长颈鹿>();</code>

The potential risk of the variance can be explained through the following example:

This code seems harmless, but it may cause accidental behavior and data damage. Assign the derived type (lion) to the base type (animal) to allow violation of type safety rules.
<code class="language-csharp">List<长颈鹿> giraffes = new List<长颈鹿>();
giraffes.Add(new 长颈鹿());
List<动物> animals = giraffes;
animals.Add(new 狮子());</code>

Although the type difference of the reference type check during the array supports the runtime, the generics are designed to achieve the safety of the type of compilation.

Introduction of security variance support in C# 4, but only limited to interfaces and commissioned commission. Coordinates are allowed to be used for Func

and Ienumeration

, and inverters are allowed to use . For the solution of C# 2.0, it is recommended to use list

.convertall to create a new list instead of trying to modify the original list.

The above is the detailed content of Why Can't I Assign List to List in C# 2.0?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn