I am learning Anonymous Type in C#, I have understood how they are defined and used. Below is a sample code I have tried for Anonymous Type.
var myType = new {
Name = "Yasser",
City = "Mumbai"
};
Console.WriteLine("Name: {0}, Type: {1}", myType.Name, myType.City);
My Question
Where in real world scenario, will these be used ? Can anyone give me an example or scenario where these Anonymous Type could be used.
What Are Anonymous Types in C#? Anonymous types are class-level reference types that don't have a name. They allow us to instantiate an object without explicitly defining a type. They contain one or more read-only properties. The compiler determines the type of the properties based on the assigned values.
Understand anonymous types in C# Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class. As shown in the below example, the Geeks class contains four properties that are A_no, Aname, language, and age.
From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
LINQ queries use them a lot:
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
The { prod.Color, prod.Price }
is an anonymous type that has a read-only Color
and Price
property. If you would iterate through the results of that query you could use that type as any other class:
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
In other words, you didn't have to define a new class that would look something like this:
public class ColoredPricedItem
{
public Color {get;}
public Price {get;}
}
Even more, Color
and Price
types are correctly inferred from your query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With