Anonymous type equality
Anonymous type equality is given by the
Equals instance method. Two objects are equal if they have the same type and equal values (through
a.Prop.Equals(b.Prop)) for every property.
Two anonymous types are considered the same if and only if their properties have the same name and type and appear in the same order.
Anonymous vs dynamic
Anonymous types allow the creation of objects without having to explicitly define their types ahead of time, while maintaining static type checking.
dynamic has dynamic type checking, opting for runtime errors, instead of compile-time errors.
Creating an anonymous type
Since anonymous types are not named, variables of those types must be implicitly typed (
If the member names are not specified, they are set to the name of the property/variable used to initialize the object.
Note that names can only be omitted when the expression in the anonymous type declaration is a simple property access; for method calls or more complex expressions, a property name must be specified.
Generic methods with anonymous types
Generic methods allow the use of anonymous types through type inference.
This means LINQ expressions can be used with anonymous types:
Implicitly typed arrays
Arrays of anonymous types may be created with implicit typing.
Instantiating generic types with anonymous types
Using generic constructors would require the anonymous types to be named, which is not possible. Alternatively, generic methods may be used to allow type inference to occur.
In the case of
List<T>, implicitly typed arrays may be converted to a
List<T> through the
ToList LINQ method:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0