I\'ve been using Visual Basic for quite a while and have recently made the decision to begin learning C# as a step forward into learning more complex languages.
As a
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
Indexers are defined using the this
keyword like this:
public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
The .NET class library design guidelines recommend having only one indexer per class.
You can overload indexers based on the indexing parameter type
public int this[int i]
public string this[string s]
but not based on the return value
// NOT valid
public int this[int i]
public string this[int i]
I don't think you can specify a property only accessible with indexing, but you could just return an indexable value (like an array or List
) and use []
on the result:
public List<Aclass> Aproperty
{
get
{
return this.theList;
}
}
Aclass foo = this.Apropety[0];
Of course, anything with an indexer will work instead of List
.
Or, you could do it the other way around: define an indexer (on the class itself) that returns an object that has a property Aproperty
, used like so: Aclass foo = this[0].Aproperty
.
Since C# doesn't support parameterized properties (which is what you are showing), you need to convert this code to two functions, a GetAProperty(index) and a SetAProperty(index).
We converted a 50,000+ LOC application from VB to C# and it required extensive modifications like this due to the dependence on parameterized properties. However, it is doable, it just requires a different way of thinking about properties like this.