Home >Backend Development >C++ >Can Anonymous Classes Be Stored in C# Generic Lists?
Anonymous Classes in Generic Lists
In C# 3.0, you have the flexibility to define anonymous classes using the syntax:
var o = new { Id = 1, Name = "Foo" };
A common question arises as to whether it's possible to store these anonymous classes in a generic list. Let's explore this issue.
Consider the following example:
var o = new { Id = 1, Name = "Foo" }; var o1 = new { Id = 2, Name = "Bar" }; List list = new List(); list.Add(o); list.Add(o1);
An alternative scenario involves adding anonymous classes within a loop:
List<var> list = new List<var>(); while (...) { .... list.Add(new { Id = x, Name = y }); .... }
Solution:
To resolve this, you can utilize an approach like:
var list = new[] { o, o1 }.ToList();
Alternatively, you can employ type inference using generic methods:
public static List<T> CreateList<T>(params T[] elements) { return new List<T>(elements); } var list = CreateList(o, o1);
Implementing these techniques allows you to effectively manage anonymous classes within generic lists.
The above is the detailed content of Can Anonymous Classes Be Stored in C# Generic Lists?. For more information, please follow other related articles on the PHP Chinese website!