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.
Definition. Anonymous type, as the name suggests is a type that doesn't have any name. Anonymous types are the new concept in C#3.0 that allow us to create new type without defining them. This is a way to define read only properties into a single object without having to define type explicitly.
What is Anonymous Types in C#? Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.
The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler.
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"
};
However, it doesn't stop e.g. the ASP.NET MVC Team you use them as a Hashtable-style parameter object...
Url.Action(new{controller="Home", action="Index"})
Which I wouldn't encourage, though, because of heavy use of magic strings.
I almost exclusively use anonymous types in LINQ-statements where in the same method you iterate over the resultset. That is pretty much why they were introduced
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With