views:

107

answers:

3

Hi,

How do square brackets in a method declaration fit in with c#? That is I see when reading up on WPF validation one can use IDataErrorInfo with an example of the following.

public string this[string propertyName]

// Error handling takes place here.
public string this[string propertyName]  // <== IE HERE
{
  get
  // etc 
  }
}

I note MSDN says "Square brackets ([]) are used for arrays, indexers, and attributes. They can also be used with pointers." So is the above usage a pointer?

+4  A: 

This is a declaration of an Indexer. It's analagous to array indexing. propertyName is a string which the method uses to index into some kind of collection. The method returns the corresponding string from the collection.

Of course, the method could do something else, but that's what the semantics mean.

Andrew Cooper
+5  A: 

This is a standard feature of the C# language called an Indexer. Generally you would use these when writing your own collections, or similar types. Here is a brief (not real world) example.

public class Foo {
    private List<int> m_Numbers = new List<int>();

    public int this[int index] {
        get {
            return m_Numbers[index];
        }
        set {
            m_Numbers[index] = value;
        }
    }
}

class Program {
    static void Main() {
        Foo foo = new Foo();
        foo[0] = 1;
    }
}

There's a lot of cool things you can use indexers for if you are creative, it's a really neat feature of the language.

David Anderson
Only let's not be *too* creative. Indexers are meant to look like array indexes and act like them, too.
Steven Sudit
+1  A: 

That would be an indexer property. They're useful on custom collections:

public class MyCustomCollection
{
    List<MyObject> _list = new List<MyObject>();

    public string this[string name]
    {
        get { return _list.Single(o => o.Name == name)
                          .Select(o => o.Description);
    }

    public string this[int id]
    {
        get { return _list.Single(o => o.Id == id).Select(o => o.Description);
    }
}

And then you can use the collection like:

MyCollection col = new MyCollection();

// Fill the collection

string description = col["Name"];
string description2 = col[2];
Justin Niessner