Anonymous types are a feature of
C# 3.0,
Visual Basic .NET 9.0,
Oxygene,
Scala and
Go that allows
data type
In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these ...
s to encapsulate a set of properties into a single object without having to first explicitly define a type.
This is an important feature for the
SQL-like
LINQ feature that is integrated into C# and VB.net. Since anonymous types do not have a named type, they must be stored in
variables declared using the
var
keyword, telling the C# compiler to use
type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
for the variable. The properties created are read-only in C#, however, they are read-write in VB.net.
This feature should not be confused with
dynamic typing
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
. While anonymous types allow programmers to define fields seemingly "on the fly," they are still static entities. Type checking is done at compile time, and attempting to access a nonexistent field will cause a compiler error. This gives programmers much of the convenience of a dynamic language, with the type safety of a
statically typed language.
Examples
C#
var person = new ;
Console.WriteLine(person.lastName);
Output:
Go
var person struct
person.firstName = "John"
person.lastName = "Smith"
OCaml
let person = object val firstName = "John" val lastName = "Smith" end;;
Oxygene
var person := new class(firstName := 'John', lastName := 'Smith');
PHP
$person = new class
;
Scala
val person = new
Visual Basic .NET
Dim person = New With
See also
*
Extension method
*
Anonymous function
*
Expression tree
References
{{reflist
External links
C# 3.0 Language Enhancements PresentationAnonymous Types in Visual Basic 2008- Learn about the new features in Visual Basic 2008.
C Sharp programming language family
Data types