views:

31

answers:

3

How can I document the key usage in a Dictionary so that it shows in Visual studio when coding using that object?

I'm looking for something like:

/// <param name="SpecialName">That Special Name</param>
public Dictionary<string,string> bar;

So far the best attempt has been to write my own class:

public class SpecialNameDictionary : IDictionary<string, string>
{
    private Dictionary<string, string> data = new Dictionary<string, string>();

    /// <param name="specialName">That Special Name</param>
    public string this[string specialName]
    {
        get
        {
            return data[specialName];
        }
    }
}

But It adds a lot of code that doesn't do anything. Additionally I must retype every Dictionary method to make it compile.

Is there a better way to achive the above?

+1  A: 

Document the field like this:

/// <summary>
/// A map from the special name to the frongulator.
/// </summary>
public Dictionary<string,string> bar;

(I assume that in reality it's either not public or not a field - but the same would apply for private fields or public properties.)

You won't get IntelliSense on the indexer itself, but any usage of bar should make it reasonably clear.

Three other alternatives:

  • Use types which make the usage clearer (a string could be anything, but a FrongulatorSpecialName is clearer)
  • Make the name of the field/property itself clearer
  • Hide the dictionary, but add a method such as "GetFrongulatorBySpecialName"
Jon Skeet
A: 

You could inherit directly from Dictionary<> instead of IDictionary<>, that way you only need to re-implement the indexer.

Matti Virkkunen
+1  A: 

You can define, dictionary like this:

public class SpecialNameDictionary : Dictionary<string, string>
{
    /// <param name="specialName">That Special Name</param>
    public new string this[string specialName]
    {
        get
        {
            return base[specialName];
        }
    }
}

Instead of deriving from IDictionary derive from Dictionary, and make new implementation of indexer.

anantmf
Thanks! I did try something like that in between my two examples but override didn't work and I forgot the new keyword.
phq