Interface member with "this" keyword

c#, design-patterns, interface, oop

Solution

It enables you to do things like:

SettingsManager settings = new SettingsManager();
var setting = settings["my setting"];

A common use is with the `List<T>` class.

It has the definition:

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
    // ....

    public T this[int index] { get; set; }

    // ....
}

This allows you to 'index' the internal values in a similar way to an array.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace test
{
    static class Program
    {
        static void Main()
        {
            List<string> myStrings = new List<string>();

            myStrings.Add("abc");
            myStrings.Add("def");

            Console.WriteLine(myStrings[0]); // outputs: "abc"
            Console.WriteLine(myStrings[1]); // outputs: "def"

            Console.Read();
        }
    }
}

Problem

While going through our client's code, I came across below interface in C#, which is having a member with "this" keyword. ``` public interface ISettings { string this[string key] { get; } } ``` I am not aware of any such pattern or practice where interface member name starts with "this". To understand more, I checked the implementation of this interface, however still not able to figure out its purpose. ``` internal class SettingsManager : ISettings { public string this[string key] { get { return ConfigurationManager.AppSettings[key]; } } ... ... } ``` And here is the caller code: ``` public static class Utility { public static ISettings Handler { get; set; } public static string Get(string key, string defaultValue) { var result = Handler[key]; return Is.EmptyString(result) ? defaultValue : result; } } ``` Unfortunately, I am not able to debug this code to see the things live. But very curious about it. If the implemented code is finally returning a string, then what is the use of "this" keyword out there?

Original source