Anonymous Types

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.



Anonymous types are inline defined types to group related values together in a single block. An anonymous type can only be used inside the body of a method. Defining an anonymous type is as simple as using new class or new record.

var lUser := new class(Name := 'Peter', Age := 49);
Console.WriteLine(lUser.Name+' is ' + lUser.Age + ' years old');

Here a new anonymous class is defined with two members. Name and Age. Name is a string and Age is an integer. Optionally a type can be used, like:

var lUser := new class(Name: String := 'Peter', Age: Double := 49);
Console.WriteLine(lUser.Name+' is ' + lUser.Age + ' years old');

The name of a member in an anonymous type can also be inferred from the value, usually from the name of a variable or property, like:

var
  lUser := new class(Data.Name, Data.Value);

This will create a new anonymous class with two members, Name and Value. Delphi Prism will emit an error when the name of the last identifier is unclear, or cannot be inferred.

Internally an anonymous class is a special generic type in the private implementation details section of the executable. This class has an internal name that's not a valid identifier and can't be used directly. Anonymous classes are often used in combination with LINQ queries to only return the relevant data in the simplest syntax as possible.


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox