22

I know C# well, but it is something strange for me. In some old program, I have seen this code:

public MyType this[string name]
{
    ......some code that finally return instance of MyType
}

How is it called? What is the use of this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
viky
  • 17,275
  • 13
  • 71
  • 90

4 Answers4

34

It is indexer. After you declared it you can do like this:

class MyClass
{
    Dictionary<string, MyType> collection;
    public MyType this[string name]
    {
        get { return collection[name]; }
        set { collection[name] = value; }
    }
}

// Getting data from indexer.
MyClass myClass = ...
MyType myType = myClass["myKey"];

// Setting data with indexer.
MyType anotherMyType = ...
myClass["myAnotherKey"] = anotherMyType;
Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
  • This answer would be more complete if you showed the property get (and/or set) accessor in your "....some code" block. This suggests it's more like a method. – Reed Copsey Mar 25 '10 at 16:36
  • And made much much less common by having built in generic collections that cover most folks' needs. No need to write your own strongly typed collections to get standard behavior anymore. – Jim L Mar 25 '10 at 17:01
7

This is an Indexer Property. It allows you to "access" your class directly by index, in the same way you'd access an array, a list, or a dictionary.

In your case, you could have something like:

public class MyTypes
{
    public MyType this[string name]
    {
        get {
            switch(name) {
                 case "Type1":
                      return new MyType("Type1");
                 case "Type2":
                      return new MySubType();
            // ...
            }
        }
    }
}

You'd then be able to use this like:

MyTypes myTypes = new MyTypes();
MyType type = myTypes["Type1"];
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

This is a special property called an Indexer. This allows your class to be accessed like an array.

myInstance[0] = val;

You'll see this behaviour most often in custom collections, as the array-syntax is a well known interface for accessing elements in a collection which can be identified by a key value, usually their position (as in arrays and lists) or by a logical key (as in dictionaries and hashtables).

You can find out much more about indexers in the MSDN article Indexers (C# Programming Guide).

Paul Turner
  • 38,949
  • 15
  • 102
  • 166
0

It's an indexer, generally used as a collection type class.

Have a look at Using Indexers (C# Programming Guide).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hath
  • 12,606
  • 7
  • 36
  • 38