Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
You create anonymous types by using the new
operator together with an object initializer.
The following example shows an anonymous type that is initialized with two properties named Amount
and Message
.
var v = new { Amount = 108, Message = "Hello" };
// Rest the mouse pointer over v.Amount and v.Message in the following
// statement to verify that their inferred types are int and string.
Console.WriteLine(v.Amount + v.Message);
Anonymous types are typically used in the select
clause of a query expression to return a subset of the properties from each object in the source sequence (LINQ в C#).
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null
, an anonymous function, or a pointer type.
Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var.
You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example.
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};
Anonymous types are class
types that derive directly from object
, and that cannot be cast to any type except object
.
Anonymous types support non-destructive mutation in the form of with expressions. This enables you to create a new instance of an anonymous type where one or more properties have new values:
var apple = new { Item = "apples", Price = 1.35 };
var onSale = apple with { Price = 0.79 };
Console.WriteLine(apple);
Console.WriteLine(onSale);
Anonymous types do override the ToString method, concatenating the name and ToString
output of every property surrounded by curly braces.
var v = new { Title = "Hello", Age = 24 };
Console.WriteLine(v.ToString()); // "{ Title = Hello, Age = 24 }"
Source: https://learn.microsoft.com/ru-ru/dotnet/csharp/fundamentals/types/anonymous-types