C # -Indexed Properties?

I have been using Visual Basic for a long time and recently decided to start learning C # as a step forward in learning more complex languages.

As part of this transition, I decided to convert some of my old VB projects manually into C #. The problem I ran into is converting a library having a class using properties with arguments / indexes.

In VB, the property will be something like this:

Friend Property Aproperty(ByVal Index As Integer) As AClass Get Return Alist.Item(Index) End Get Set(ByVal value As KeyClass) Alist.Item(Index) = value End Set End Property 

When I used the property, it will be used as follows:

 Bclass.Aproperty(5) = new AClass 

This is what I want to achieve in C #, but I canโ€™t understand how much I can do this, since C # cannot do this.

+4
source share
3 answers

Since C # does not support parameterized properties (this is what you are showing), you need to convert this code into two functions: GetAProperty (index) and SetAProperty (index).

We converted the 50,000 + LOC application from VB to C # and required large modifications like this because of the dependence on parameterized properties. However, this is doable; it just requires a different way of thinking about such properties.

+4
source

Indexers allow you to index instances of a class or structure as arrays. Indexers resemble properties, except that their accessors accept parameters.

http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

Indexers are defined using the this as follows:

 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; } } 

Recommendations for developing a .NET class library recommend that you have only one index for each class.

You can overload indexers based on the type of index parameter

 public int this[int i] public string this[string s] 

but not based on return value

 // NOT valid public int this[int i] public string this[int i] 
+4
source

I donโ€™t think you can specify a property that is accessible only with indexing, but you can just return the index value (for example, an array or List ) and use [] for the result:

 public List<Aclass> Aproperty { get { return this.theList; } } Aclass foo = this.Apropety[0]; 

Of course, anything with an index will work instead of List .

Or you could do it the other way around: define an indexer (by the class itself) that returns an object with the Aproperty property, which is used like this: Aclass foo = this[0].Aproperty .

+1
source

All Articles