views:

104

answers:

3

I have no clue what an "anonymous type" is in C# nor how it is used. Can somone give me a good description of it and it's use?

[Note: i really know what it is and how to use it but thought i'd ask for those that don't]

+7  A: 

An anonymous type is a type generated by the compiler due to an expression such as:

new { Property1 = x.Value1, Property2 = y.Value2, z.Value3 }

(the last one is like Value3 = z.Value3).

The name of the anonymous type is "unspeakable" - i.e. you can't specify it in normal C# - but it's a perfectly normal type as far as the CLR is concerned. As you can't write the name, if you want to create a variable of an anonymous type (or a generic type using an anonymous type as the type argument), you need to use an implicitly typed local variable with the var keyword:

var person = new { Name = "Bill", Address = "..." };

C# anonymous types are immutable (i.e. the properties are read-only) - the generated type has a single constructor which takes values for all the properties as parameters. The property types are inferred from the values.

Anonymous types override GetHashCode, Equals and ToString in reasonably obvious ways - the default equality comparer for each property type is used for hashing and equality.

They are typically used in LINQ in the same way that you'd use "SELECT Value1 As Property1, Value2 As Property2, Value3" in SQL.

Every anonymous type initializer expression which uses the same property names and types in the same order will refer to the same type, so you can write:

var x = new { Name = "Fred", Age = 10 };
x = new { Name = "Bill", Age = 15 };

It's also worth knowing that VB anonymous types are slightly different: by default, they're mutable. You can make each individual property immutable using the "Key" keyword. Personally I prefer the C# way, but I can see mutability being useful in some situations.

Jon Skeet
You learn something new every day. I had no idea they were immutable and override `GetHashcode`, `Equals` and `ToString`. What do they override ToString with?
jasonh
@jasonh: Comma separated values in braces, e.g. { X = 2, Y = 10 }
Jon Skeet
Uh oh. Someone has hacked Jon Skeet's account and stolen his rep and badges and stuff! ;)
RCIX
A: 

An anonymous type is a type that has no name. You can use it anywhere you don't need the name of the type. For instance:

var query = from x in set where x.Property1 = value select new {x.Property1, x.Property2};
foreach (var q in query) {
    // do something with q.Property1, q.Property2
}
John Saunders