Anonymous type ( English Anonymous types ) is one of the innovations in C # 3.0, Visual Basic .NET 9.0 and Oxygene , which allows data types to encapsulate a set of properties in a single object without the need for preliminary explicit type specification [1] . This is one of the most important features of the SQL-like language LINQ , integrated into C # and VB.net. Since anonymous types do not support typing names, they must be stored in variables declared using the var keyword, which tells the C # compiler to use type inference for this variable. Such properties in C # are read-only, but in VB.net they are also available for change (read-write).
Content
Comparison with dynamic typing
This feature should not be confused with dynamic typing . Despite the fact that anonymous types allow the programmer to define fields on the fly, they still remain static entities. Type checking is performed at compile time, and attempting to access a nonexistent field will cause a compilation error. This allows the programmer to take advantage of the convenience of a dynamic language along with the safety of types of languages ββwith static typing .
Examples
C # language
var person = new { FirstName = "Ivan" , LastName = "Ivanov" }
var size = new { Heigth = 7 , Weigth = 5 , Depth = 5 }
Visual Basic .NET
Dim person = New With {. FirstName = "Ivan" ,. LastName = "Ivanov" }
In Oxygene
var person: = new class (FirstName: = 'Peter', LastName: = 'Petrov');
OCaml
let person = object val firstName = "Peter" val lastName = "Petrov" end ;;
Criticism
One of the main drawbacks of the anonymous type in C # 3.0 is the inability to export it outside the method in which it was created. This restriction is due to the inherited restrictions of the .NET Framework 2.0 CLR, which did not provide anonymous types. As a result, it is impossible to resolve a name conflict when exporting an anonymous type with a matching signature, and accordingly, an anonymous type cannot be made visible outside the assembly. The restriction on methods is imposed because they can be exported to other assemblies, which would cause the described problem [2] .
See also
- Extension method
- Anonymous function
- Parsing tree
Notes
- β Anonymous Types (C # Programming Guide) . Microsoft Date of treatment November 25, 2008. Archived July 23, 2012.
- β C # 3.0 and LINQ. Concepts of C # 3.0, which allowed to create LINQ (Russian)