Tutorial by Examples

Since anonymous types are not named, variables of those types must be implicitly typed (var). var anon = new { Foo = 1, Bar = 2 }; // anon.Foo == 1 // anon.Bar == 2 If the member names are not specified, they are set to the name of the property/variable used to initialize the object. int foo ...
Anonymous types allow the creation of objects without having to explicitly define their types ahead of time, while maintaining static type checking. var anon = new { Value = 1 }; Console.WriteLine(anon.Id); // compile time error Conversely, dynamic has dynamic type checking, opting for runtime ...
Generic methods allow the use of anonymous types through type inference. void Log<T>(T obj) { // ... } Log(new { Value = 10 }); This means LINQ expressions can be used with anonymous types: var products = new[] { new { Amount = 10, Id = 0 }, new { Amount = 20, Id = 1 }, ...
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. var anon = new { Foo = 1, Bar = 2 }; var anon2 = new { Foo = 5, Bar = 10 }; List<T> CreateList<T>(params T[] it...
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. var anon = new { Foo = 1, Bar = 2 }; var anon2 = new { Foo = 1, Bar = 2 }; var anon3 = new { Foo = 5, Bar = 10 }; ...
Arrays of anonymous types may be created with implicit typing. var arr = new[] { new { Id = 0 }, new { Id = 1 } };

Page 1 of 1