Net-informations.com
SiteMap  | About    

What is anonymous type ?

anonymous type C# vb.net

Anonymous types are useful to hold information in the local scope temporarily. It is a new concept in C# 3.0 which allows to create new types without defining them. These types are created on the fly typically in order to return results in a LINQ statement. Anonymous types are reference types derived form system.objects and properties of the Anonymous type are read only.

One can define Anonymous types easily by using new keyword of C#.

var vr = new { Name = "Jack", Age = 22 };

Here the statement to verify that their inferred types are int and string.

Console.WriteLine(vr.Name + vr.Age);

LINQ

Since anonymous types do not have a named typing, they must be stored in variables declared using the var keyword, telling the C# compiler to use type inference for the variable. In the following example, the names of the properties of the anonymous type are Name and Age.

var studentQuery = from stud in students select new { stud.Name, stud.Age }; foreach (var v in studentQuery) { Console.WriteLine("Name={0}, Age={1}", v.Name, v.Age); }

anonymous properties

Anonymous types are useful for returning several properties from a query without having to define a type explicitly for that purpose. If two Anonymous types have the same properties and same order, then the compiler treats it as the same type, but if both are in one assembly.







net-informations.com (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.