-1

I'm trying to figure out what does this [string name] mean in the declaration public string this[string name]

Complete Code :

public class PersonImplementsIDataErrorInfo : IDataErrorInfo
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Error
    {
        get
        {
            return "";
        }
    }

    public string this[string name]
    {
        get
        {
            string result = null;

            if (name == "Age")
            {
                if (this.age < 0 || this.age > 150)
                {
                    result = "Age must not be less than 0 or greater than 150.";
                }
            }
            return result;
        }
    }
}

Source

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Freddykong
  • 95
  • 12
  • 4
    It is an [indexer](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/using-indexers). It provides usage like `personImplementsIDataErrorInfoInstance["name"]` – Fildor Nov 19 '19 at 09:19
  • 2
    @HimBromBeere Would you mind changing the dupe target to [this one](https://stackoverflow.com/questions/30511571/meaning-of-this-int-index). That looks to be a better match – NathanOliver Nov 21 '19 at 15:17

1 Answers1

5

It's an indexer.

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.

In this case, the PersonImplementsIDataErrorInfo class contains an indexer of type string, that will return a string based on whatever string you send it -

If you send it Age, it will return either null or "Age must not be less than 0 or greater than 150.", if the age property is less than 0 or more than 150.

Consider the following code:

var person = new PersonImplementsIDataErrorInfo() { Age = 167 };

Console.WriteLine(person["Something"]);
Console.WriteLine(person["Age"]);

This will result with one blank line (since Something will return a null string) and one line that reads "Age must not be less than 0 or greater than 150."

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121