Generating C# indexers
C# introduces a new concept known as indexers, which are used for treating an object as an array. Indexers are usually known as smart arrays in the C# community.
An indexer is a member that enables objects to be indexed in the same way as an
array. An indexer is declared like a property except that the name of the
member is "this" followed by a parameter list written between
the delimiters [ and ]. The parameters are available in the
accessor(s) of the indexer. Similar to properties, indexers can be read-write,
read-only, and write-only, and the accessor(s) of an indexer can be virtual.
Indexers can be overloaded, meaning that a class can declare multiple indexers
as long as the number or types of their parameters differ.
Indexers are modeled through a UML class with two operations, "get"
and "set", to which the <<CsIndexer>>
stereotype is added.
A class stereotyped <<CsIndexer>> will not be generated. It will
simply be used to generate C# indexer get and set signatures and bodies.
The following is a description of indexer accessors:
· "get": The "get" operation has parameter(s). This (these) parameter(s) allow the indexed research in your array.
· "set": The "set" operation has at least two parameters, and must have the value to set for the right-hand parameter.
These functions help to resolve the indexer signature. Indexer signatures are as follows:
Indexer-visibilityindexer-returnType this[indexer-parameters] { … }
"indexer-visibility" is defined by the class visibility.
"indexer-returnType" is defined by the "get"
operation return parameter or by the "set" operation
right-hand parameter.
"indexer-Parameters" are defined by the "get"
operation parameter(s) or by the "set" operation parameters
except the right-hand one, corresponding to the value to be defined.
|
UML
model |
C#
generated |
|
|
using System; using System.Collections; namespace csIndexerSample { public class cImageContainer { public ArrayList images = new ArrayList();
/* cMyIndexer
*/ public string this[int index] { get { return images.GetValue(index); } set { images.SetValue(index, value); } } } } |
Note 1: Embedded classes cannot be visualized in Objecteering Modeler.
Note 2: Generation only takes the "get" and "set" operations of a "CsIndexer" and discards everything else.