Anonymous types
Last updated
Last updated
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.
You create anonymous types by using the operator together with an object initializer.
Anonymous types typically are used in the clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see .
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.
The most common scenario is to initialize an anonymous type with properties from another type.
Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using . The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type. For more information about var
, see .
You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example.
Anonymous types are types that derive directly from , and that cannot be cast to any type except . The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
Because the and methods on anonymous types are defined in terms of the Equals
and GetHashCode
methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.