Anonymous Types in C#

Introduction:

The Anonymous type, as the name suggests, is actually objects that have an unknown type. In other words, whose type is not known to us. Only the compiler can get its type during the compilation of the code.

In C# as we all know there is a var keyword in reference to implicitly typed variables.

This var when used with the new keyword creates an Anonymous types object, whose type is only known to the compiler during the compilation of the code.

Description

An Anonymous Type is actually a nameless class that inherits from objects.

Simply, we can say that an anonymous type is a reference to a nameless class as created. In other words, we can use it as we use a simple reference of a class and that class doesn't actually exist.

You will get a better understanding from a simple example.

Suppose in your program you needed an object having a person's First Name, Middle Name and Last Name. For this what we basically do is to create a class Person having the fields or properties FirstName, MiddleNAme and LastName. However for this simple program you don't need to create a separate class for this, you can do this using this Anonymous types. What we need to do is to create a simple Anonymous type having the person's FIrstName, MiddleName and LastName as in the following:

  1. var batsman = new { FirstName=”Sachin”, MiddleName=”Ramesh”, LastName=”Tendulkar”};  
If you want to create another person object having the same properties you can do this :
  1. var bowler = new { FirstName=”Ravindra”, MiddleName=”Chandran”, LastName=”Ashwini”};  
So what we see here is that to do such type of simple things we don't need to always create a separate class. We can do that job with the Anonymous Types also, but it has the major drawback that we can't get its types.

We can also put values inside the properties (FirstName, MiddleName and LastName) from the other class.

So that's all for the theory portion. Now its time for us to get our hand dirty with writing some code, so that we better grasp the concept of Anonymous Types.

Agenda 
  • Create a Console C# Project
  • Create the Anonymous Types
  • Create a Class containing some properties
  • Show the result of the created class using Anonymous type
  • Show the Output in the Console Window
Step 1

Create a new Console C# Project name it as per your convenience (I named it “AnonymousTypes”).

Console application

Step 2

Add a class to the project (name “Cricketer.cs”) and add three fields in it of type string (FirstName, MiddleName and LastName).

Add a class in the project

Add the following Line of code to "Cricketer.cs":
  1. class Cricketer  
  2. {  
  3.      public string FirstName = "Ravindra";  
  4.      public string MiddleName = "Singh";  
  5.      public string LastName = "Jadeja";  
  6. }  
Step 3

In the Program.cs file add the following line of code:
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         //Creating an Anonymous type batsman having properies FirstName  
  6.         //MiddleName and LastName  
  7.         var batsman = new { FirstName = "Sachin", MiddleName = "Ramesh", LastName = "Tendulakar" };  
  8.   
  9.         //Similarly Creating an Anonymous Types for bowler having properties  
  10.         //First Name, Middle Name and Last Name  
  11.         var bowler = new { FirstName = "Ravindra", MiddleName = "Chandran", LastName = "Ashwini" };  
  12.   
  13.         //Printing Name of Batsman  
  14.         Console.WriteLine("Batsman");  
  15.         Console.WriteLine("First Name: {0}\nMiddle Name: {1}\nLast Name: {2}", batsman.FirstName, batsman.MiddleName, batsman.LastName);  
  16.   
  17.         //Printing Name of Bowler  
  18.         Console.WriteLine("\nBowler");  
  19.         Console.WriteLine("First Name: {0}\nMiddle Name: {1}\nLast Name: {2}", bowler.FirstName, bowler.MiddleName, bowler.LastName);  
  20.   
  21.   
  22.         //Using Class(Cricketer.cs) Properties Inside the Anonymous Type object  
  23.         //Creating an Instance of the Cricketer class  
  24.         Cricketer cricketer = new Cricketer();  
  25.         var allrounder = new { FirstName = cricketer.FirstName, MiddleName = cricketer.MiddleName, LastName = cricketer.LastName };  
  26.   
  27.         //Printing Name of AllRounder  
  28.         Console.WriteLine("\nAll Rounder");  
  29.         Console.WriteLine("First Name: {0}\nMiddle Name: {1}\nLast Name: {2}", allrounder.FirstName, allrounder.MiddleName, allrounder.La        stName);  
  30.         Console.ReadKey();  
  31.     }  
  32. }  
That's all. Compile and run the project, if everything works fine then you will get the following output window:

run the project

I hope you have gotten the concept of “Anonymous Types”.

If you have any query or suggestions then feel free to comment.

I am including the source code.

Thanks.


Recommended Free Ebook
Similar Articles