Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#-Indexed Properties?

Tags:

c#

vb.net

c#-4.0

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 part of this jump I have decided to convert a few of my old VB projects by hand into C#. The issue I am having is with converting a library that had a class using properties with arguments/indexes.

The property would be something like this in VB:

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 would be used like this:

Bclass.Aproperty(5) = new AClass

It is this sort of thing I want to achive in C# but cannot figure out for the life of me just how to do this as it seems C# can't do this sort of thing.

like image 462
Pharap Avatar asked Jan 15 '23 23:01

Pharap


2 Answers

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.

like image 74
competent_tech Avatar answered Jan 25 '23 00:01

competent_tech


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]
like image 35
Eric J. Avatar answered Jan 24 '23 22:01

Eric J.