2

I'm going through someone else's code and I saw this statement:

public CustomClassName this [ string varName]

Please excuse the newbness of this question, but the square brackets threw me off. Is this a method or constructor?

How does the "this" variable work in this case?

Ray
  • 3,409
  • 8
  • 33
  • 40

5 Answers5

6

It's called an indexer. MSDN page.

Bala R
  • 107,317
  • 23
  • 199
  • 210
  • So that's how it's done! VB.NET's `Default` is a lot more clear :) – Ry- Sep 15 '11 at 18:43
  • @minitech: Highly debatable. I haven't come across a single construct in VB that I thought was more clear than it's C# allegory. – Ed S. Sep 15 '11 at 18:45
1

Neither, it's an Indexer. It allows you to do CustomClassName[ obj ] and retrieve a value from the object.

Brandon Moretz
  • 7,512
  • 3
  • 33
  • 43
0

It is an indexer, so you can access the class similar to an array.

tcarvin
  • 10,715
  • 3
  • 31
  • 52
0

It is defining an index operator on your type. Take for example, the List<T> class. The library designers wanted you to be able to write code like this:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };
int x = list[2]; // x == 3

The syntax that accomplishes that is what you have posted above. So, for your own types, you can...

class NameCollection : /* whatever */
{
    private List<string> _names = new List<string> { "Ed", "Sally", "John" };

    public string this[int index]
    {
        get { return _names[index]; }
    }
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
0

this is simply an overload of the square-bracket operator in C#.

see here:

How do I overload the square-bracket operator in C#?

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147