How to create Anonymous type in C#
Anonymous type in C#
In this
article we will discuss about anonymous type in C#. This concept has introduced
in C # 3.0 versions. Basically anonymous concept is used to crate data type at
runtime. There is no need to create any user define data type (like
class or structure) previously. In the example below we will see how to create
anonymous type in C#.
Create
simple anonymous type.
To create
anonymous type we will use var keyword. As, we don’t know actual type of
anonymous variable using new keyword we will
initiate few members in anonymous type.
using System;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
namespace BridgeDesign
{
class Program
{
static void Main(string[] args)
{
var MyClass = new { name = "Sourav", surname = "Kayal" };
Console.WriteLine("Name:- "+ MyClass.name);
Console.WriteLine("Surname:- " + MyClass.surname);
Console.ReadLine();
}
}
}
Here is
sample output.

How it works in background?
Let’s
discuss a little how anonymous type converts in strong type. Here a class without
a name is generated with two data member. For anonymous type syntax
the compiler generates a class. The class contents those variables which are
declared within new block. In compile time compiler make it as strong type
class and Visual Studio Intellisense supports anonymous type. Because when we
try to access member of anonymous type we can get help from Intellisense like
below.

Use one
anonymous type within other anonymous type
We can use
one anonymous type within other anonymous type like below.
using System;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
namespace BridgeDesign
{
class Program
{
static void Main(string[] args)
{
var MyStudent = new { name = "Sourav", surname = "Kayal" };
var ClassRoom = new { MyStudent.name, MyStudent.surname, ClassRoom = "MCA"
};
Console.WriteLine("Student Name:- "+ ClassRoom.name);
Console.WriteLine("Student surname:- " + ClassRoom.surname);
Console.WriteLine("Class Name:- " + ClassRoom.ClassRoom);
Console.ReadLine();
}
}
}
Here is
sample output

Conclusion:
This is
basic idea about anonymous type in c#. Hope you have understood the concept.