Diggie
Diggie

Reputation: 142

anonymous types, when is it useful?

How could this anonymous type be useful in real life situation? Why is it good to be anoynimous?

// sampleObject is an instance of a simple anonymous type.
var sampleObject = 
    new { FirstProperty = "A", SecondProperty = "B" };

Upvotes: 1

Views: 107

Answers (2)

horgh
horgh

Reputation: 18534

From MSDN Anonymous Types (C# Programming Guide):

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.

...

The most common scenario is to initialize an anonymous type with properties from another type.

For extra info, you may read Anonymous Types in Query Expressions.

Also, consider reading SO What is the purpose of anonymous types?


Consider an example from How to: Join by Using Composite Keys (C# Programming Guide):

var query = from o in db.Orders
            from p in db.Products
            join d in db.OrderDetails
                on new { o.OrderID, p.ProductID } 
            equals new { d.OrderID, d.ProductID } 
            into details
            from d in details
            select new { o.OrderID, p.ProductID, d.UnitPrice };

This example shows how to perform join operations in which you want to use more than one key to define a match. This is accomplished by using a composite key. You create a composite key as an anonymous type or named typed with the values that you want to compare.


And an example of using anonymous types for grouping dara to encapsulate a key that contains multiple values from Group by Multiple Columns using Anonymous Types in LINQ to SQL:

var months = from t in db.TransactionData
             group t by new { month = t.Date.Month, year = t.Date.Year } 
                into d
             select new { t.Key.month, t.Key.year };

or beter How to: Group Query Results (C# Programming Guide):

An anonymous type is used because it is not necessary to use the complete object to display the results

Note that the properties in the anonymous type become properties on the Key member and can be accessed by name when the query is executed.

Upvotes: 3

D J
D J

Reputation: 7028

Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).

Upvotes: 1

Related Questions