Anonymous
In general anonymous types of declared with var keyword like
var a =10;
var b=20.5;
var c=” sai”;
What we use the data type in C# like int, string, double, etc. are known as “named types”.
Anonymous types are introduced in 2.0 versions of .net framework and C#.
Anonymous types cannot be used as Global variables.
Initialize the data into an anonymous type is mandatory.
Inclined to build a profession as ASP.net Developer? Then here is the blog post on, explore ASP.net Training
Different between Anonymous and Named types
Named Type | Anonymous |
| Type is known at compile time |
| Compiler will decide the type of the variable |
| Use var keyword to create a variable with an anonymous type |
| Can be used as a local variable only and can’t be used as a global variable data field of the class |
| Can be used in the following situations
|
| Initialization of variable is mandatory |
| In case of number types cannot be used with increment/ decrement unary operator -> for a = a++ produces compile-time error |
| Multiple variables can’t be declared in the same statement as var a=10,b= “sai” raises compilation error |
| Can’t be used with unsafe code |
| Support complex types |
Examples with Anonymous types:
Name space CA sample{
Class sample
{
Static void main ()
{
Var a=”10”;
Var b=”sai”;
Var c=”10.5”;
c.w.l(“value of a :-“+a);
c.w.l(“value of b :-“+b);
c.w.l(“value of c :-“+c);
console.read();
}
}
}
Create an array and print elements using Anonymous type?
Name space CA sample{
Class sample
{
Static void main ()
{
Int []A=new int [6]{10,20,30,40,50,60};
String []B=new string[3]{“sai”,”Ram”,”krishna”};
c.w.l(“elements of array A are:-”);
for each (var X in A)
c.write (X+” “);
c.wl (“/n element of array B are:-“);
for each (var X in B)
console write (X+” “);
console read ();
}
}
}
Name space CA sample
{
Class example3
{
Static void main ()
{
Var Pname =New {Sname=”Sachin”, Fname=”Ramesh”, Lname=”tendulker”};
Var DOB=new {Day=14, month=”April”, year=1973};
c.w.l(“person name is:-”+Pname.fname+Pname.Lname);
c.w.l(“DOB is:-”+DOB.month+”-”+DOB.year);
c.Read();
}
}
}
For in-depth understanding click on
- ASP. NET web applications and ASP. NET MVC Application.
- Object initialization
- Razor syntax
- Collection Initialize ASP.net
- View engine & Razor view engine