0

While searching for C#'s equivalent to Java's Hashmap, I came across a sliver of code that I've never seen before. Was hoping someone could explain the signature of the property definition in this class.

public class NullableDictionnary : Dictionary<string, string>
{
    string null_value;


    public StringDictionary this[string key]
    {
        get
        {
            if (key == null) 
            {
                return null_value;
            }
            return base[key];
        }
        set
        {
            if (key == null)
            {
                null_value = value;
            }
            else 
            {
            base[key] = value;
            }
        }
    }
}

Specifically, what is meant by this[string key] ?

Joe
  • 797
  • 1
  • 10
  • 23
  • 4
    This is called an [Indexer](http://msdn.microsoft.com/en-us/library/2549tw02.aspx) – Arian Motamedi Mar 04 '14 at 19:41
  • http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx – SLaks Mar 04 '14 at 19:41
  • 2
    This could be hard to search on google, You can use http://symbolhound.com/ to search, look at the [result](http://symbolhound.com/?q=this%5Bstring+key%5D+C%23) for `this[string key] C#` – Habib Mar 04 '14 at 19:44

2 Answers2

5

That is called indexer. You can read the documentation:

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Basically that allows you to access your elements with an index.So in this case you can acess your NullableDictionnary elements like this:

NullableDictionnary[key]

key should be a string because your class inherits from Dictionary<string, string>.

Normally if you pass a null key to an indexer of a Dictionary<TKey, TValue> you will get an ArgumentNullException.But here you are extending this indexer and returning a default value when the key passed as null.For example this will throw ArgumentNullException:

var dict = new Dictionary<string, string>();
Console.WriteLine(dict[null]); // ArgumentNullException

But this will not:

 var dict = new NullableDictionnary();
 Console.WriteLine(dict[null]);

That will write value of null_value variable.And a last note, you should change returning type of indexer to string instead of StringDictionary otherwise it won't compile.

 public string this[string key]
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

This is an indexer property. Essentially providing implementation of [] operator. More at MSDN

LB2
  • 4,802
  • 19
  • 35