DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Anonymous Types

Let’s talk about Anonymous Types, introduced in C# 3, which allow you to create lightweight and temporary objects with named properties without needing to explicitly define a class. See the example in the code below.

public class Program
{
    public static void Main()
    {
        var product = new { Name = "Pen", Price = 2.99m };

        Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

Anonymous Types are useful when you need to temporarily store a set of data with properties but don’t want to create a specific class for it. They are widely used in LINQ queries, where the result is composed of different types of data that don’t need to be persisted.

This feature allows for quick and efficient object creation, providing a concise way to represent data without explicit class definitions, making the code more agile and easier to write.

Source code: GitHub

I hope this tip helps you use Anonymous Types to simplify handling temporary data in your projects! Until next time.

Top comments (0)