Home > Backend Development > C++ > Can Anonymous Classes Be Added to Generic Lists in C#?

Can Anonymous Classes Be Added to Generic Lists in C#?

DDD
Release: 2025-01-04 07:21:35
Original
556 people have browsed it

Can Anonymous Classes Be Added to Generic Lists in C#?

Adding Anonymous Classes to a Generic List in C

In C# 3.0, anonymous classes provide a convenient way of creating lightweight objects with dynamically generated properties. However, the question arises: can these anonymous classes be incorporated into generic lists?

List Compilation Techniques

To address this, you have a few options:

  1. Initialization Array: You can create an anonymous class array and then use the .ToList() method to convert it to a list.

    var list = new[] { o, o1 }.ToList();
    Copy after login
  2. Generic Method with Type Inference: By using a generic method, you can avoid explicitly specifying the list type.

    public static List<T> CreateList<T>(params T[] elements)
    {
        return new List<T>(elements);
    }
    
    var list = CreateList(o, o1);
    Copy after login

Example Usage

Let's provide some working examples:

// Example 1: Adding to an Existing List
var list = new List<dynamic>();
list.Add(new { Id = 1, Name = "Foo" });
list.Add(new { Id = 2, Name = "Bar" });

// Example 2: Populating a List in a Loop
var list = new List<dynamic>();

while (...)
{
    list.Add(new { Id = x, Name = y });
}
Copy after login

In these scenarios, the anonymous classes are effectively added to the generic list. Please note that the type of the list remains dynamic, allowing for the addition of anonymous classes with different property sets without type validation.

The above is the detailed content of Can Anonymous Classes Be Added to Generic Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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