.net – the purpose of anonymous types

.net, anonymous-types

What are the best use cases for anonymous types?

It would seem to me that they are only useful within a limited context, for example one class or one function. They can hardly be used outside of this context, because without reflection no one will know what properties are available on these types.

Best Solution

Anonymous types are intended to only be used in very narrow scopes. Most use cases that I've had for them involve Linq.

var result = from x in MyCollection             select new              {                 x.Prop1,                  x.Prop2             };

Also, in the case of Linq to SQL - using anonymous types will generate different SQL by selecting only the columns that are used in the anonymous type. In the case above (if it were a Linq to SQL query), it would generate something like "select prop1, prop2 from mytable" instead of selecting all of the fields.

I've never run across (yet) a situation where I wanted to just declare a new anonymous type in my code. I suppose if anything else, maybe it would be a good use for local constants?

var x = new        {            FirstName = "Scott",            LastName = "Ivey"        };