0

I want to implement getter & setter property access in Dictionary like below,

int _number;
public int Number
{
    get
    {
        return this._number;
    }
    set
    {
        this._number = value;
    }
}

Please help me if there any solution to implement getter & setter to dictionary because one of the app we use static dictionary for localization and that used whole application. In get method I will check if passed key not found then it return key. Now problem is that if in dictionary key is not found then it gives exception "Key not found".

Thanks in advance!

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
Kishor T
  • 300
  • 1
  • 4
  • 15
  • Maybe take a look at a similar [Question on SO](https://stackoverflow.com/questions/11583595/how-to-write-a-getter-and-setter-for-a-dictionary?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Cataklysim May 18 '18 at 05:05
  • 2
    Possible duplicate of [How to write a getter and setter for a Dictionary?](https://stackoverflow.com/questions/11583595/how-to-write-a-getter-and-setter-for-a-dictionary) – AsthaUndefined May 18 '18 at 05:06
  • 1
    There are already methods which you can use instead of reinventing the wheel.https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx for the use case you mentioned in the question `ContainsKey` is the useful method for you. It will return true or false based on if the key exists in the dictionary or not. – Chetan May 18 '18 at 05:07
  • @AsthaSrivastava how we implement get method, mentioned article implemented the only Set method. I want to handle condition only in get method only. – Kishor T May 18 '18 at 05:27
  • 1
    You can use `TryGetValue` which returns `false` if the key is not present and true if it is present.Your value will be an `out` variable. – Bercovici Adrian May 18 '18 at 05:28

1 Answers1

3

A Dictionary already has methods for safe attempting to retrieve values.

You can use ContainsKey, that returns true if the key is found in the keys collection or false if not,
or you can use TryGetValue, that takes as an out argument TValue and returns true if found, and false if not.
You don't need to add functionality to a dictionary, just to learn how to use it's existing functionality properly.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • I know the existing functionality but things is that while code review jr. developer user localization dictionary used complete application without checking condition. And it is difficult to replace/add that condition in complete application. If there is any way to use setter & getter then it would be feasible to change at declaration level. – Kishor T May 18 '18 at 05:34
  • 2
    I don't see how something like your proposal will help - you will still need to find all the places in the code that access the dictionary values and change them... – Zohar Peled May 18 '18 at 05:46