Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this[string key] mean

Tags:

c#

I looked at IRequestCookieCollection code from Microsoft.AspNetCore.Http assembly:

  //
  // Summary:
  //     Represents the HttpRequest cookie collection
  [DefaultMember("Item")]
  public interface IRequestCookieCollection : IEnumerable<KeyValuePair<string, string>>, IEnumerable
  {
    //
    // Summary:
    //     Gets the value with the specified key.
    //
    // Parameters:
    //   key:
    //     The key of the value to get.
    //
    // Returns:
    //     The element with the specified key, or string.Empty if the key is not present.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    //
    // Remarks:
    //     Microsoft.AspNetCore.Http.IRequestCookieCollection has a different indexer contract
    //     than System.Collections.Generic.IDictionary`2, as it will return string.Empty
    //     for missing entries rather than throwing an Exception.
    string this[string key] { get; }

    //
    // Summary:
    //     Gets the number of elements contained in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     The number of elements contained in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    int Count { get; }
    //
    // Summary:
    //     Gets an System.Collections.Generic.ICollection`1 containing the keys of the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     An System.Collections.Generic.ICollection`1 containing the keys of the object
    //     that implements Microsoft.AspNetCore.Http.IRequestCookieCollection.
    ICollection<string> Keys { get; }

    //
    // Summary:
    //     Determines whether the Microsoft.AspNetCore.Http.IRequestCookieCollection contains
    //     an element with the specified key.
    //
    // Parameters:
    //   key:
    //     The key to locate in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     true if the Microsoft.AspNetCore.Http.IRequestCookieCollection contains an element
    //     with the key; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    bool ContainsKey(string key);
    //
    // Summary:
    //     Gets the value associated with the specified key.
    //
    // Parameters:
    //   key:
    //     The key of the value to get.
    //
    //   value:
    //     The key of the value to get. When this method returns, the value associated with
    //     the specified key, if the key is found; otherwise, the default value for the
    //     type of the value parameter. This parameter is passed uninitialized.
    //
    // Returns:
    //     true if the object that implements Microsoft.AspNetCore.Http.IRequestCookieCollection
    //     contains an element with the specified key; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    bool TryGetValue(string key, out string value);
  }

and could not understand what the statement

this[string key]

means. Could someone explain me please.

like image 399
softshipper Avatar asked Jul 20 '16 07:07

softshipper


People also ask

How do you give an object a key to type?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings. Copied!


2 Answers

It's an indexer. It defines an indexed property that can be used to access a collection of the object by using objectName["key"] like for example a Dictionary<string,T>.

The implementation could look something like this:

string this[string key]
{ 
    get{return _internalDictionary[key];}
}

Or this:

string this[string key]
{ 
    get
    {
        switch(key)
        {
            case "Length":
                return this.Length;
            case "Timeout":
                return this.Timeout.ToString();
            case "Version":
                return "1.5.0";
        }
        return null;
    }
}
like image 81
Manfred Radlwimmer Avatar answered Sep 21 '22 06:09

Manfred Radlwimmer


It's just like a method but different

This is really just a special kind of function. For example imagine you had this class:

class MyClass {
    public string GetValue(string name) {
        switch(key)
        {
            case "Name":
                return "John";
            case "Age":
                return 30;
        }
    }
}

The way you would call this code would of course be this:

// Calling a regular method
var instance = new MyClass();
var value = instance.GetValue("Name");
Console.WriteLine(value);
// Output: John

Now change a couple of things so that you are using the "indexer" syntax instead.

  1. Instead of using the method name "GetValue", use the "this" keyword.
  2. Instead of parenthesis around your parameters, use square brackets

Applying those steps:

  • string GetValue(string name) becomes
  • string this[string name]

To make it a little easier to envision imagine that your original function instead of being called GetValue() was called This(), then:

  • string This(string name) becomes
  • string this[string name]

Full code:

class MyClass {
    // public string GetValue(string name) {
    public string this[string name] {
        switch(key)
        {
            case "Name":
                return "John";
            case "Age":
                return 30;
        }
    }
}

In terms of calling your indexer, you drop the function name and again use square brackets instead of parenthesis. So that instance.GetValue("Name") becomes instance["Name"].

Full code:

// Calling a regular method
var instance = new MyClass();

// Remove the dot (.) and the function name
// Instead of parenthesis use square brackets

// var value = instance.GetValue("Name");
var value = instance["Name"];

Console.WriteLine(value);
// Output: John

When should you use an indexer instead of a method?

Whenever you want. Whenever you feel it makes sense. It's usually used when an object stores dynamic keyed values like Dictionary<TKey,TValue>, or when you want your object to behave like an array like List.

like image 45
Luis Perez Avatar answered Sep 19 '22 06:09

Luis Perez