Hello Friends, Anonymous types were introduced in C# 3.0. You must know C# anonymous types if you want to learn and get working knowledge in LINQ In this article I will help you to understand the C# anonymous types and their utilization in the programming with code examples.
How to create C# Anonymous types
Anonymous type is a simple class or reference type created by the compiler at the run time. It stores a set of values based on the identifiers used while creating the type.
It uses object initializer syntax to create a type. The exact syntax would be the new keyword followed by object initializer syntax.
The properties of the anonymous type are read only. After creation or initilization they cannot be changes.
Simple anonymous type with four properties is present in the below code example.
var Person = new { FirstName = "Vikram", LastName = "Chaudhary", DOB = new DateTime(2018, 08, 18), Place = "India" };
Its not mandatory to initialize and assign the property values while creating an anonymous type.
We can use already existing variables to and they will act as the property names. Below is code examples for the same.
string FirstName = "Vikram"; string LastName = "Chaudhary"; DateTime dob = new DateTime(2018, 08, 18); string Place = "India"; var Person = new { FirstName, LastName, dob, Place, FirstName.Length};
The property name of the anonymous type can be inferred from an expression that is itself an identifier or ends with one. Length is one more property present in the above code example. It is created by the Length property of the string and takes the same name.
You can create arrays of anonymous type as shown in the below code example:
var people = new[] { new { Name = "Vikram", Age = 37 }, new { Name = "Peter" , Age = 57} };
Anonymous type Equality
We need take care while comparing anonymous types. If any two or more anonymous type have the same order, number and member declaratory type and name, they refer to same anonymous type class.
We will have a look at some examples to understand it better.
var person = new { FirstName = "Vikram", LastName = "Chaudhary" }; var person1 = new { FirstName = "Vikram", LastName = "Chaudhary" }; var person2 = new { FN = "Vikram", LastName = "Chaudhary" }; var person3 = new { LastName = "Vikram", FirstName = "Chaudhary" }; Console.WriteLine(person.Equals(person1)); //True, everything is same Console.WriteLine(person.Equals(person2)); //False, member declaration name different Console.WriteLine(person1.Equals(person2));// False, member declaration name different Console.WriteLine(person.Equals(person3)); //False, member declaration in different order Console.WriteLine(Object.ReferenceEquals(person, person1));
As you can see in the above code, I have used the Equals method to check equality. The hash created will be same if type, order and name of the member decelerators are same
Please note that above code does not mean that two instances refer to same instance. The references will be different. The last line checks for the reference equality and it returns false.
When to use C# Anonymous types
The most common use case scenario for C# anonymous type is in LINQ query creation and result manipulation.
Below is a simple code to use the C# Anonymous type. In this code I have created an anonymous type which has two properties.
var processes = Process.GetProcesses().Select(item => new { Name = item.ProcessName, item.PagedMemorySize64 });
We are able to work with the LINQ queries with the help of extension methods and lambda expressions.
Finally C# anonymous types help us to not create custom class for each LINQ query thus writing less code.
They can be used to hierarchical data as well as custom collections.
Passing C# Anonymous types as parameter to method
Since C# anonymous type are derived from Object type. They can be passed as parameter to a method accepting object as argument.
Below is a simple code example.
static void Main(string[] args) { var person = new { FirstName = "Vikram", LastName = "Chaudhary" }; }); WriteProperties(person) } private static void WriteProperties(object input) { Type tyepName = input.GetType(); PropertyInfo[] info = tyepName.GetProperties(); foreach (var item in info) { var value = item.GetValue(input); } }
We have to use the Reflection to get the property and their values. Since we don’t have user defined types that is why we have to do it dynamically at run time.
Conclusion and Summary:
- C# anonymous types are used to create user defined reference types at run time.
- They are derived from the object base class.
- If the order, name and type of properties are same, the types are considered as equal.
- They can be passed as parameter to the method.
- We have to use reflection to get the values of properties at run time.
I hope this article will help you to understand the C# anonymous types.
Leave a Reply