PDA

View Full Version : Anonymous Types or Class in C#


DotNet
05-02-2010, 06:28 PM
Definition:

Anonymous types (known as anonymous class in Java), are classes which have no name. These classes are read-only, as you can't change anything in the class anywhere else other than declaration.

or in more technical words:

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

Declaration:

var x = new { ANumber = 1, Message = "Hello" };

here a class is declared automatically by compiler, which has no name, but just two properties. if we try to edit these values anywhere else in the code, compiler will generate an error.

Usage:

Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.

abhishek
06-02-2010, 06:39 AM
Anonymous classes are also there in Java.. JavaGuru where are you? Please explain..