-1
public class TestClass
{
    private Dictionary<string, int> _testDictionary = new Dictionary<string,int>();

    private string _key;

    public int this[string key]
    {
        get { return _testDictionary[key];}
        set 
        {
            if (_testDictionary.ContainsKey(key))
                _testDictionary[key] = value;
            else
                _testDictionary.Add(key, value);
        }
    }

}

public class Program
{
        static void Main(string[] args)
        {
            TestClass test = new TestClass();
            test["T1"] = 1;
            test["T2"] = 2;

            Console.WriteLine(test["T1"]);
            Console.WriteLine(test["T2"]);
        }

}

So how this way of defining properties is called, I want to read more about that. Also is it possible to have same definition like this in other places, for an example in Methods etc.

mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • maybe, do you mean "getters" and "setters"? – Fattie Feb 19 '16 at 18:07
  • 5
    I think you mean "Indexers" or "Indexed properties": http://www.dotnetperls.com/indexer this may be of use when creating your own datastructure. – Max Feb 19 '16 at 18:08
  • I mean this part public int this[string key] – mybirthname Feb 19 '16 at 18:08
  • @mybirthname I'd call it gross :/ – Kritner Feb 19 '16 at 18:08
  • @Max can I use this type of declaration on other places or just for properties. You can post your comment as an answer, I will upvote it for sure and probably mark it as correct if no one answers anything else. – mybirthname Feb 19 '16 at 18:40
  • What "other places" did you have in mind? I can't think of other uses at this moment. I can give you an example of when and how you could use it though. – Max Feb 19 '16 at 19:01
  • No no worries I read the article which you give as a source powt as ana answer and I will mark it as correct – mybirthname Feb 19 '16 at 19:03

2 Answers2

1

Your implementation is right, you could add your desired IndexerName but you don't have to. It is better to add a guide from the getter in case the key is not found, and you return some default value.

Check out this enter link description here

public class TestClass
{
    private Dictionary<string, int> _testDictionary = new Dictionary<string, int>();

    // you do not need a private property to store the key
    // private string _key;

    [IndexerName("MyKeyItem")]
    public int this[string key]
    {
        get
        {
            if (_testDictionary.ContainsKey(key))
            {
                return _testDictionary[key];
            }

            return int.MinValue;
        }

        set
        {
            if (_testDictionary.ContainsKey(key))
                _testDictionary[key] = value;
            else
                _testDictionary.Add(key, value);
        }
    }
}
Community
  • 1
  • 1
Lin Song Yang
  • 1,936
  • 19
  • 17
1

It's called an indexed property.

Kyle W
  • 3,702
  • 20
  • 32