Powered by Blogger.

Sunday, February 23, 2014

Anonymous Types in C#.Net



In this post we will discuss about Anonymous types in C#.Net. Anonymous types are newly introduced in C#.Net 4.0.

Also check out:

- How to display serial number automatically in GridView in asp.net?

- How to check strength of password using PasswordStrength AjaxControlToolkitExtender in asp.net?

- Lock and Monitor statement in C#.Net

According to MSDN: Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.

We can create anonymous types by using the new operator together with an object initializer like below:

Example:

var people = new { ID = 1, Name = "AspDotNetHelp" };

Now you can access like below:

Console.WriteLine(people.ID + people.Name);

Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.





0 comments

Post a Comment