Anonymous Types In LINQ

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 

  1. 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. 

  1. 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: 

  1. 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 

  1. var myArrayWithAntype = new int[]{ 1, 2, 12, 53, 58, 8, 2113, 2221 };  
In the preceding the array is Anonymous since it is defined with the Anonymous Type initialization rule.

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. 

  1. var fullname = new {FirstName=”Gaurav”, LastName=”Arora”};  

In the preceding, "fullname" contains both first and last name. Go through the following. 

  1. //throws an error  
  2.   
  3. Console.WriteLine(fullname.FirstName);  
  4.   
  5. //Displays fullname  
  6.   
  7. Console.WriteLine(fullname); 

Note:

  1. Anonymous types are immutable.

  2. 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.


Similar Articles