In this article, we will learn how to use anonymous types in C#.
- Anonymous types were introduced in C# 3.0.
- These are data types generated on the fly at runtime.
- These data types are generated by the compiler rather than explicit class definition.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
var MyAnonClass = new
{
Name = "Scott",
Subject = "ASP.Net"
};
Console.WriteLine(MyAnonClass.Name);
Console.Read();
}
}
}
Output
A class without a name is generated and assigned to an implicitly typed local variable.
How does it work internally?
- For anonymous type syntax, the compiler generates a class.
- Properties of the class generated by the complier are value and data type given in the declaration.
- Intellisense supports anonymous type class properties.
- Properties of one anonymous type can be used in the declaration of other anonymous types.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
var MyAnonClass = new
{
Name = "Scott",
Subject = "ASP.Net"
};
Console.WriteLine(MyAnonClass.Name);
Console.Read();
var SecondAnoynClass = new
{
info = MyAnonClass.Name + MyAnonClass.Subject
};
Console.WriteLine(SecondAnoynClass.info);
Console.Read();
}
}
}
Output