Creating an anonymous type C# with Example



Creating an anonymous type C# with Example

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 = 1; 
int bar = 2; 
var anon2 = new { foo, bar }; 
// anon2.foo == 1 
// anon2.bar == 2 
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. 
string foo = "some string"; 
var anon3 = new { foo.Length }; 
// anon3.Length == 11 
var anon4 = new { foo.Length <= 10 ? "short string" : "long string" }; 
// compiler error - Invalid anonymous type member declarator. 
var anon5 = new { Description = foo.Length <= 10 ? "short string" : "long string" }; 
// OK 

0 Comment's

Comment Form

Submit Comment