Anonymous Type (Var)
Anonymous type use the keyword var. The var introduce with .net 3.5 indicates an anonymous type. The var keyword signals the compiler to emit a strong type based on the value of the operator on the right side. var adds punch is by initializing composite types on the fly, such as those returned from LINQ queries. When such an anonymous type is defined, the compiler emits an immutable-read only properties-class referred to as projection. The following list include some basic rules for using anonymous types:
• Anonymous types must always have an initial assignment and it can’t be null
• Composite Anonymous types require member declarators; for example var item=new {title=”computer”, proce=”12220.00”};
• Anonymous types support IntelliSence.
• Anonymous type can’t be use for class field.
• Anonymous types can be used as initializers in for loop
• The new keywords can be used and has to be used for array initializers.
• Anonymous types can used with arrays
• Anonymous types are all derived from the Object type.
• Anonymous type can be returned from methods but must be cast to object.
Defining Simple Anonymous type
Var title=”LINQ the most usable technology in .net 3.5”
Using Array Initializer Syntax
Var fibona=new int[]{1,1,2,3,5,8,13,21,34,55,89};
Ex:
Var fibona=new int[]{1,1,2,3,5,8,13,21,34,55,89};
foreach (var f in fibona)
Console.WriteLine(f);
foreach (var f in from fb in fibona where fb % 3 == 0 select fb)
Console.WriteLine(f);
Create Composite Anonymous Type
Var item=new{title=”Computers”, Prise=”32570.00”};
Ex.:
var clsArr = new { FName = “Jitendra”, LName = “Kumar” };
Console.WriteLine(clsArr.FName.ToString());
Console.WriteLine (clsArr.LName.ToString());
Anonymous Return by Method
var a = GetVar();
Type t = a.GetType();
PropertyInfo[] inf = t.GetProperties();
Response.Write(inf[1].GetValue(a, null));
public object GetVar()
{
var stock = new {Items=”Mobile”,Price=”1500.00″};
return stock;
}
Anonymous data binding
var item1 = new {item=”Computer”,Prise=25990.00};
var item2 = new { item = “Laptop”, Prise = 32899.00 };
var item3 = new { item = “L CD TV”, Prise = 32000.00 };
var item4 = new { item = “AC”, Prise = 19721.00 };
var item5 = new { item = “Mouse”, Prise = 225.00 };
var item6 = new { item = “Printer”, Prise = 980000.00 };
var item7 = new { item = “UPS”, Prise = 1600.00 };
var item8 = new { item = “Monitor”, Prise = 5000.00 };
var item9 = new { item = “CVT”, Prise = 3200.00 };
var item10 = new { item = “Pen Drive”, Prise = 400.00 };
var items = new object[]
{ item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
item9,
item10
};
GridView1.DataSource = items;
GridView1.DataBind();
Quote get from Yahoo
var strURL = @”http://download.finance.yahoo.com/d/quotes.csv?s=XOM+EK+JNJ+MSFT&f=snd1t1l1ohgvwdyr“;
var wr = WebRequest.Create(strURL);
var rs = wr.GetResponse();
var sm = rs.GetResponseStream();
var sr = new StreamReader(sm, Encoding.ASCII);
Console.WriteLine(sr.ReadToEnd().ToString());