Wikipedia

Anonymous type

Anonymous types are a feature of C# 3.0, Visual Basic .NET 9.0, Oxygene, Scala and Go that allows data types to encapsulate a set of properties into a single object without having to first explicitly define a type.[1] 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 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. 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

PHP

$person = new class {  public $firstName = "John";  public $lastName = "Smith"; }; 

C#

var person = new { firstName = "John", lastName = "Smith" }; Console.WriteLine(person.lastName); 

Output: Smith

Visual Basic .NET

Dim person = New With {.firstName = "John", .lastName = "Smith"} 

Oxygene

var person := new class(firstName := 'John', lastName := 'Smith');

OCaml

let person = object val firstName = "John" val lastName = "Smith" end;; 

Scala

val person = new { val firstName = "John"; val lastName = "Smith" } 

Go

var person struct { firstName string; lastName string } person.firstName="John" person.lastName="Smith" 

See also

References

  1. ^ "Anonymous Types (C# Programming Guide)". Microsoft. Archived from the original on 7 December 2008. Retrieved 2008-11-25.

External links

This article is copied from an article on Wikipedia® - the free encyclopedia created and edited by its online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of Wikipedia® encyclopedia articles provide accurate and timely information, please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.

Copyright © 2003-2025 Farlex, Inc Disclaimer
All content on this website, including dictionary, thesaurus, literature, geography, and other reference data is for informational purposes only. This information should not be considered complete, up to date, and is not intended to be used in place of a visit, consultation, or advice of a legal, medical, or any other professional.