C#: Anonymous Type is not anonymous!
Why Anonymous Type?
Anonymous types provide you the ease of having set of properties (Read only) into a single object without knowing the type. It’s the job of compiler to generate the type information.
Anonymous types can be created by using the keyword new. Say:
var test = new { Name = “Jackie”, ID = 123 };Here ‘var’ keyword plays an important role as the type information won’t be available.
Anonymous types are mostly used with the query expressions. This type can contain one or more Pubic read only properties.
The most common scenario where Anonymous types are useful is shown below:
var details = from data in dt.AsEnumerable()
select new
{
UID = data.Field("id"),
FirstName = data.Field("fName"),
LastName = data.Field("lName”),
Mobileno = data.Field("mno"),
Address = data.Field<string>("add")
};Here, the DataTable dt already has some members or properties say. Now let’s say you don’t need to have all the properties or members of dt.
Then in that case we will make use of Anonymous type using the new keyword. This causes smaller amount of data to be dealt with.
Here we have specified the member names to the upcoming Anonymous type (UID, FirstName etc..)which is not necessary. If at all, we are not passing any names to the members, compiler will use the name of the members of the existing type(id, fname, lname etc..).
As this article is based on developer’s experience so Please provide more inputs to improve this article.









