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
Release: 2025-01-11 08:42:40
Original
780 people have browsed it

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:

public abstract class Data<T> { }

public class StringData : Data<string> { }

public class DecimalData : Data<decimal> { }
Copy after login

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

List<Data> dataCollection = new List<Data>(); // Compiler error!
dataCollection.Add(new DecimalData());
dataCollection.Add(new StringData());
Copy after login

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:

public interface IData { void SomeMethod(); }

public abstract class DataBase { public abstract void SomeMethod(); }
Copy after login

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

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();
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template