Search code examples
c#asp.net-mvcbracketssquare

What is the purpose of 'arguments' in square brackets? C#


I ran into this while watching a tutorial. Haven't seen it before, and I'd like to know what's going on here.

    Application["ApplicationStartDateTime"] = DateTime.Now;

Here it is in context:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        Application["ApplicationStartDateTime"] = DateTime.Now;
    }
    protected void Application_End()
    {
        Application.Clear();
    }
}

The application_Start method is boiler plate except for the StartDateTime line that was added with little explanation as to why. Specifically, I want to know about the square brackets. I'm aware of arrays, and I'm aware of annotations, but this looks different.


Solution

  • That's an indexer. Basically it's meant to look like the use of an array, but it can have multiple parameters, and they don't have to be integers. Just like a property, an indexer can have a get accessor and/or a set accessor.

    They're declared like this:

    public class Container
    {
        public string this[int x, int y]
        {
            get { /* code here */ }
            set { /* code here using value */ }
        }
    }
    

    That's an indexer of type string that has two int parameters. So we could then write:

    Container container = new Container();
    string fetched = container[10, 20];
    container[1, 2] = "set this value";
    

    Indexers are most commonly used for collections:

    • IList<T> declares a read/write indexer of type T with a single int parameter
    • IDictionary<TKey, TValue> declares a reader/write indexer of type TValue with a single TKey parameter