-1

I don't understand this C# code:

    public virtual object this[string fullname]
    {
        get
        {
            return null;
        }
        set
        {
        }
    }  

Specifically the this[string name] part. What is the person intending this code to do? Here is how it's implemented later:

   public override object this[string fullname]
    {
        get
        {
            fullname= fullname.Trim('\"');
            //some code ....
            return x;
        }
        set
        {
            fullname= fullname.Trim('\"');
            //some code ...
            string[] a= fullname.Split(":".ToCharArray());
            //some more code...
        }
    }

Is the person redefining the this keyword whenever it's used by the class that has this code? Is that what's going on? If so why?

BarnumBailey
  • 391
  • 1
  • 4
  • 13
  • this defines an "indexer" - i.e. so other code can do `someObj["whatever"] = blah;` - there are separate getters and setters for the indexer – Marc Gravell Dec 20 '18 at 17:20
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/ – David Dec 20 '18 at 17:20
  • `public` = public `virtual` = can be overriden `object` = can return any type `this[string fullname]` = indexer. Expected that you can call it as `object o = myClass["x"];` – T.S. Dec 20 '18 at 17:23
  • This post can help you : https://stackoverflow.com/questions/424669/how-do-i-overload-the-operator-in-c-sharp – Shim-Sao Dec 20 '18 at 17:23
  • Thanks all, not that familiar with indexers outside of their use on collections. Didn't know this was the syntax for using it in a class. – BarnumBailey Dec 20 '18 at 17:34

1 Answers1

0

that is overloading the index operator. it is used primarily on 'collection' types, like a string, array, or list. you may be familiar with it used this way:

var items = new int[] { 1, 2, 3 };
var item = items[1];

it allows you to do custom checks when someone tries to index into your type.

the addition of the virtual keyword in this case means classes that derive this type can do a custom implementation, or leave it out and default to the base class implementation you are looking at.

Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49