Anonymous types in C# 3.0
1. Anonymous types are new feature being added in C# 3.0.2. These are data types being generated on the fly at the run time.
3. These data types are generated through complier 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();
}
}
}
A class without name is being generated and assigned to implicitly type local variable
How it works internally?
1. For an anonymous type syntax compiler generates a class.
2. Properties of the complier generated class are value and data type given in declaration.
3. Intellisense supports anonymous type class properties.
4. Properties of one anonymous type can be used in declaration of another anonymous type.
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();
Console.Read();
}
}
}
Output
No comments :
Post a Comment