2

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

Basically I want to know if there is a way to achieve custom behavior for brackets similar to the SqlDataReader Object. For example with the SqlDataReader object you can use an index number "Reader[0]" which is the normal operation for brackets, or you can supply the column name "Reader["id"]". I know how to override basic operators but can not seem to find anything relating to changing bracket behavior.

Community
  • 1
  • 1
gSamp
  • 93
  • 6

1 Answers1

14

You need to define an indexer in your type

public class MyType {
  public string this[int index] {
    get { 
      switch (index) {
        case 1: return "hello";
        case 2: return "world";
        default: return "not found";
      }
    }
    set { ... }
  }
}

MyType t = ...;
Console.WriteLine(t[0]);  // hello
Console.WriteLine(t[1]);  // world
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Thanks, this is exactly what I was looking for. Sorry for the duplicate question, I keep getting strange results when I tried searching for []. – gSamp Feb 03 '12 at 16:51