Home >Backend Development >C++ >How Can I Add Anonymous Classes to Generic Lists in C#?
In C#, anonymous classes allow for convenient and concise encapsulation of data, employing a simplified syntax that omits explicit class and property declarations. However, incorporating these anonymous classes into generic lists may present a challenge.
To address this, you can leverage the Type Inference feature, which automatically deduces the generic type parameter based on the context. One approach involves creating an array of anonymous classes, such as o and o1, and subsequently converting it to a generic list using the ToList() method:
var list = new[] { o, o1 }.ToList();
Alternatively, you can define a generic method to construct a list from a variable-length parameter list, as seen below:
public static List<T> CreateList<T>(params T[] elements) { return new List<T>(elements); }
With this method, you can instantiate a list of anonymous classes using the generic type parameter T and pass the anonymous classes as arguments:
var list = CreateList(o, o1);
These options rely on type inference to determine the generic type, offering a straightforward way to create generic lists of anonymous classes.
The above is the detailed content of How Can I Add Anonymous Classes to Generic Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!