4

I'm converting Visual Basic.Net code to C# in my project. But I have some doubts on how to convert Visual Basic default property to C#. The first option that comes to me are the indexers. Lets imagine the next code in Visual Basic

Public Class MyClass
Dim MyHash as Hashtable

Public sub New()
    MyHash = New Hashtable()
    MyHash.Add("e1",1)
    MyHash.Add("e2",2)
    MyHash.Add("e3",3)
End Sub

Defaul Propery MyDefProp(ByVal key as string) as Object
  Get
    Return MyHash(key)
  End Get

  Set(ByVal ObjectToStore As Object)
    MyHash(key) = ObjectToStore
  End Set
End Property

Converted this to C#:

public class MyClass
{
    private Hashtable MyHash;

    public MyClass()
    {
        MyHash = new Hashtable();
        MyHash.Add("A1",1);
        MyHash.Add("A2",2);
        MyHash.Add("A3",3);
    }

    public object this[string key]
    {
        get
        {
            return MyHash[key]; 
        }

        set
        {
            MyHash[key] = value;
        }
    }     
}

Am I correct on this?

aligray
  • 2,812
  • 4
  • 26
  • 35
JAVH
  • 155
  • 1
  • 3
  • 13

3 Answers3

5

You are correct.

The only difference is that the VB.Net version also creates a named indexed property; C# does not support named indexed properties.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

While C# does support the default property syntax, your indexer will meet that need nicely.

agent-j
  • 27,335
  • 5
  • 52
  • 79
  • Indexers _are_ default properties. – SLaks Jun 13 '11 at 23:16
  • My VB is a bit rusty, but I don't think that you are forced to have an indexed default property. For example the Text property was the default for TextBox, and it is not an indexed probperty. – agent-j Jun 13 '11 at 23:30
  • VB.NET supports 'indexed' properties that are not the default property. Properties can have an arbitrary number of arguments, unlike C#. – Hans Passant Jun 14 '11 at 01:48
0

As of 2022 you absolutely can index a class by name in C#. Just add this to your class definition:

public object this[string key]
{
   get { return this.GetType().GetProperty(key).GetValue(this, new object[0]); }
}

You can add a setter to this and your no longer stuck with just dot notation