1

I ran into this C# code which apparently allows me to access the object's properties in a single method by their name in an input string. I assume its a relatively new C# feature. Can someone tell me what it's called and the reference to the documentation?

    public class ExamValidation : Exam, IDataErrorInfo
    {

//...
        public string this[string columnName]
        {
//---
        }
    }
D Stanley
  • 149,601
  • 11
  • 178
  • 240
andre.barata
  • 663
  • 3
  • 11

3 Answers3

4

It's called an indexer and it is not new - it has been in C# from the beginning. It's simply another way of looking up data in a collection (by string rather by an integer index).

It's found in data structures where the order of elements in not as important as looking up data by a string key, such as a dictionary or data table (looking up row data by column name instead of order).

D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

This is called an indexer and it's not new at all. These have been around since the first iteration of the framework. Indexers are commonly seen with int values, like an array for example, but they can receive any type. Note the documentation:

Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

So, in this case it's looking up data with a string.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

This is telling me that the class has an indexer so you can save an array/list of values.

PCG
  • 1,197
  • 9
  • 23