Search code examples
c#idataerrorinfo

c# - how do square brackets in a method declaration fit in with c#?


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?


Solution

  • 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.