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]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
An anonymous type is a type generated by the compiler due to an expression such as:
(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
varkeyword: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,EqualsandToStringin 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:
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.