none
About a syntax RRS feed

  • Question

  • Hello everybody,

    In the code of an interface, I find this :

            //
            // Summary:
            //     Gets or sets a configuration value.
            //
            // Parameters:
            //   key:
            //     The configuration key.
            //
            // Returns:
            //     The configuration value.
            string this[string key] { get; set; }
    

    Hum, can anybody explain me ?

    Is there a difference with just

    string key {get; set;}

    ?

    Is it an index ?

    In the code of an extension method I remember seeing this in the first parameter, but this does not seem to be the same.

    Monday, September 16, 2019 3:30 PM

Answers

  • Yes, it's an index.  If you say:

        string key { get; set; }

    then you would use it like this:
        obj.key = "123";
        Console.WriteLine( obj.key );

    But when you say:
        string this[string key] { get; set; }

    The property "this" requires an index parameter, like this:
        obj.this["123"] = "456";
        Console.WriteLine( obj.this["123"] );


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by Gloops Monday, September 16, 2019 5:25 PM
    Monday, September 16, 2019 4:22 PM

All replies

  • Yes, it's an index.  If you say:

        string key { get; set; }

    then you would use it like this:
        obj.key = "123";
        Console.WriteLine( obj.key );

    But when you say:
        string this[string key] { get; set; }

    The property "this" requires an index parameter, like this:
        obj.this["123"] = "456";
        Console.WriteLine( obj.this["123"] );


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by Gloops Monday, September 16, 2019 5:25 PM
    Monday, September 16, 2019 4:22 PM
  • Thanks a lot.

    So as I understand, if I change the key, potentially I get all the properties different.

    Monday, September 16, 2019 5:24 PM
  • In regards to extension methods see the following example with summary.

    https://github.com/karenpayneoregon/LanguageExtensions/blob/master/ExtensionsLibrary/GenericExtensions.cs#L31


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, September 16, 2019 6:00 PM
    Moderator