Anonymous Types
Anonymous Types are custom types (Classes Records or Interfaces) that are instantiated on the fly, without being explicitly declared or given a name (hence, anonymous). This is done by combining the new
keyword with class
, record
or interface
instead of a concrete type name:
Anonymous Classes or Records
An anonymous classes or records declaration is followed by parentheses containing one1 or more Property Initializers, which for an anonymous class function both to declare and initialize the property.
var x := new class(Name := "Peter", Age := 35);
The above code declares a new variable x
which holds an instance of an unnamed class with two properties, Name
, of type String and Age
of type Integer.
The class can then be used in normal fashion, accessing (or changing) the value of its properties, or doing further processing on it.
Variables initialized to an anonymous type instance are assignment compatible, if their parameter names and types match.
var x := new class(Name := "Peter", Age := 35);
var y := new class(Name := "Paul", Age := 28);
x := y;
Anonymous types are most frequently used in combination with the select
clause of a from
Expression, to limit the sequence to a subset of fields or combine data within each item of a sequence in new ways.
var lNamesAndAges := from p in lPersons
select new class(Name := p.Name, Age := DateTime.Today-p.DateOfBirth);
Anonymous Interface Classes
Anonymous interfaces classes provide the implementation for one or more methods of an Interface. This usage pattern is very common on the Android platform, where rather than .NET-style Events, controls usually are assigned a delegate object that implements a given interface in order to receive callbacks when events happen – such as to react to the click of a button.
Anonymous interfaces classes allow to define such a class inline and implement one or more handler methods without having to implement the interface on the containing class or providing a class who's connection to the surrounding code would need to be managed manually.
You can think of anonymous interface classes as an extension or a more sophisticated version of Anonymous Methods. In fact, an anonymous method is considered the same as an anonymous interface class with just one method.
And just like anonymous methods, code inside an anonymous interface class has full access to the surrounding scope, including full access to the containing class.
Anonymous interfaces are defined using the new interface
keyword combo, and mjust include the name of the interface being implemented:
fButton.delegate := new interface IClickEvent(OnClick := method begin
// handle the click here
end);
See Also
from
Expressions- Classes and Records
- Interfaces
- Anonymous Methods
-
Technically, the anonymous type may contain zero members, but that would not be very useful. ↩