Anonymous Types in C#

The Anonymous types feature was introduced in version 3.0 of the C# language with a special purpose in mind and that purpose was to provide an easier way to define objects with a few read-only properties. 

In the traditional way, we need to create a class and define read-only properties of the class and that's it. Nothing more. So the C# development team added anonymous types to avoid the need for definition of the classes. The C# compiler understands when an anonymous type is defined. Each property of the class is inferred by the compiler. 

Anonymous types contain one or more public read-only properties. Non read-only members of the class are not valid. 

Let's look at the following code snippet. 

var annAuthor = new
{
    Name = "Mahesh Chand",
    Book = "ADO.NET Programming",
    Publisher = "APress",
    Year = 2003,
    Price = 49.95
};

As you can see in the code snippet above, there is no type defined for Name, Book, Publisher, Year, and Price. However strings, integer, and double values are assigned to these variables. This type if declaration in C# is an anonymous type declaration. 

In this code, the left side var is a type inference of a class that has read-only properties with their values assigned in the definition. 

So how does this work?

When you declare anonymous types, the compiler automatically creates a class at run-time and knows what the members of the class are with their implicit types. 

For example, if you make a call to the "annAuthor" var type defined in your code above then you will see the designer generates the definition and auto-populates the class members as you can see in the following image.

Anonymous-Types-1.jpg

As soon you call annAuthor, the read-only properties are available and the compiler also generates and explains what the anonymous types and their data types are.

The following image shows that the compiler knows that "a" is a new with the members Name, Book, Publisher, Year, and Price. The compiler also shows that a.Book is a string type. 

Anonymous-Types-2.jpg

If you select Price then you will see it is a double type.

Anonymous-Types-3.jpg

Anonymous types are heavily used in LINQ. They saves developer's time not to write anonymous types if they are being used for this simple purpose only. 

Summary

In this article, we learned about anonymous types in C# and how and when to use them.



Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.