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.
LINQ queries use them a lot:
The
{ prod.Color, prod.Price }is an anonymous type that has a read-onlyColorandPriceproperty. If you would iterate through the results of that query you could use that type as any other class:In other words, you didn’t have to define a new class that would look something like this:
Even more,
ColorandPricetypes are correctly inferred from your query.