Introduction
For Visual Basic programmers the keyword "var" is confusing since type variants were used in Visual Basic in the past. Here, the keyword var tells the compiler to emit a strong type based on the value of the operation on the right side.
Important
Anonymous types can be used to initialize simple types like integers and strings.
Rules: The following are some basic rules to use LINQ Anonymous Types.
Anonymous types can't be null
They must always have an initial assignment.
They can be used with simple or complex types, but composite anonymous types require a member declaration.
Example
- var mylist = new {Topic="Anonymous-Types" [, declaratory = value, ...]}.
In the preceding topic is the member declaration.
- Supports intelliSense.
- Cannot be used for class field.
- Can be used with arrays.
- Anonymous types are all derived from the Object type.
Now, let's explore some categories or types of anonymous types.
Simple Anonymous Type
With the keyword var and giving the value of the variable in the right side of the assignment operator (=), anyone can declare a Simple anonymous type.
- var list = "Anonymous Types in LINQ : A Step Ahead Series";
The anonymous type is assigned to the name on the left side of the assignment operator and the type emitted by the compiler to the Microsoft Intermediate Language (MSIL) is determined by the right side of the operator.
The preceding line is identical in the MSIL if defined as in the following:
- var list = "Anonymous Types in LINQ : A Step Ahead Series";
Array Initializer Syntax
Anyone can use an Anonymous Type to initialize an array too but with the rigid rule that the new keyword must be used.
Example
- var myArrayWithAntype = new int[]{ 1, 2, 12, 53, 58, 8, 2113, 2221 };
Composite Anonymous Types
Let's define it.
Now, let's have a look how to define a Composite Anonymous Type. It's just called a class without the “typed” class definition.
- var fullname = new {FirstName=”Gaurav”, LastName=”Arora”};
In the preceding, "fullname" contains both first and last name. Go through the following.
- //throws an error
- Console.WriteLine(fullname.FirstName);
- //Displays fullname
- Console.WriteLine(fullname);
Note:
- Anonymous types are immutable.
- Within the scope of this article we have supplied a few tricks, there can be generic anonymous methods, you can apply methods, can return anonymous values and so on.

Gaurav Kumar AroraPosted Apr 13, 2015, 3:23 AM
Gowtham Rajamanickam - thanks
Gowtham RajamanickamPosted Apr 11, 2015, 1:22 PM
well explained
Gowtham RajamanickamPosted Apr 11, 2015, 1:22 PM
good
Shuby AroraPosted Feb 5, 2015, 2:39 PM
well defined
Saber ShaikhPosted Dec 15, 2014, 6:13 AM
good explanation
Chao HuPosted Dec 14, 2014, 11:47 PM
well down ,very cool
Shuby AroraPosted Dec 14, 2014, 4:50 AM
Good stuff , self explanatory
Jitendra KumarPosted Dec 14, 2014, 2:23 AM
Nice..
Vithal WadjePosted Dec 14, 2014, 12:54 AM
good explanation