Search code examples
c#thisintellisenseindexerconstructor-chaining

What is the purpose of the second [] in this example?


public abstract class InstallationStepLibrary
{
    private Dictionary<string, InstallationStep> DictSteps;

    protected InstallationStepLibrary()
    {
        DictSteps = new Dictionary<string, InstallationStep>();
    }

    public InstallationStep this[string s]
    {
        get
        {
            return DictSteps[s];
        }
        set
        {
            DictSteps[s] = value;
        }
    }

    protected void NewStep(string name, InstallationStep step)
    {
        this[name] = step;
    }
}

I suspect that the first use of 'this' is chaining constructors from the definition of InstallationStep, however I cannot figure out how the second 'this[name]' (which intellisense tells me scopes to the class InstallationStepLibrary, which makes sense...) can be valid syntax but it is.

It would make sense if it scoped to the Dictionary...


Solution

  • The second [] or:

    protected void NewStep(string name, InstallationStep step)
    {
        this[name] = step;
    }
    

    Just calls the indexer defined in the class. It would work the same if the caller just used:

    installationStepLibrary[name] = step;
    

    Where the indexer defined in the class is:

    public InstallationStep this[string s]
    {
        get
        {
            return DictSteps[s];
        }
        set
        {
            DictSteps[s] = value;
        }
    }