Home >Backend Development >C++ >How Can I Create a List of Open Generic Types in C#?

How Can I Create a List of Open Generic Types in C#?

DDD
DDDOriginal
2025-01-11 08:42:40699browse

How Can I Create a List of Open Generic Types in C#?

Handling Lists of Open Generic Types in C#

Working with open generic types (generics with unspecified type parameters) in C# presents challenges due to limitations in generic polymorphism.

The Challenge:

Consider these classes:

<code class="language-csharp">public abstract class Data<T> { }

public class StringData : Data<string> { }

public class DecimalData : Data<decimal> { }</code>

Attempting to create a list containing instances of these different Data types directly fails:

<code class="language-csharp">List<Data> dataCollection = new List<Data>(); // Compiler error!
dataCollection.Add(new DecimalData());
dataCollection.Add(new StringData());</code>

The compiler error arises because Data is an open generic type, requiring a type argument.

The Solution:

C#'s lack of a diamond operator prevents direct instantiation of lists of open generics. Polymorphism doesn't directly apply to open generic types. The workaround is to use a common base type or interface:

<code class="language-csharp">public interface IData { void SomeMethod(); }

public abstract class DataBase { public abstract void SomeMethod(); }</code>

Now, you can create a list using the interface or base class:

<code class="language-csharp">List<IData> dataList = new List<IData>();
dataList.Add(new StringData()); // StringData must implement IData
dataList.Add(new DecimalData()); // DecimalData must implement IData

foreach (var item in dataList)
    item.SomeMethod();


List<DataBase> dataBaseList = new List<DataBase>();
dataBaseList.Add(new StringData()); // StringData must inherit from DataBase
dataBaseList.Add(new DecimalData()); // DecimalData must inherit from DataBase

foreach (var item in dataBaseList)
    item.SomeMethod();</code>

This approach allows for a collection of different Data types, but it sacrifices strong typing compared to a truly generic solution. The SomeMethod() example highlights the need for a common interface or abstract method to maintain functionality across different types.

Further Reading:

The above is the detailed content of How Can I Create a List of Open Generic Types in C#?. 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