Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real World Example for Anonymous Types of C# .NET

Tags:

c#

.net

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.

like image 674
Yasser Shaikh Avatar asked Aug 03 '12 11:08

Yasser Shaikh


People also ask

What is an anonymous type in C?

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.

What is an anonymous object in C#?

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.

How do you utilize the anonymous type especially in Linq?

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.

What is difference between an anonymous type and regular data type?

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.


1 Answers

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.

like image 193
ipavlic Avatar answered Oct 19 '22 12:10

ipavlic