Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a getter and setter for a Dictionary?

Tags:

How do you define a getter and setter for complex data types such as a dictionary?

public Dictionary<string, string> Users {     get     {         return m_Users;     }      set     {         m_Users = value;     } } 

This returns the entire dictionary? Can you write the setter to look and see if a specific key-value pair exists and then if it doesn't, add it. Else update the current key value pair? For the get, can you return a specific key-value pair instead of the whole dictionary?

like image 957
Mausimo Avatar asked Jul 20 '12 16:07

Mausimo


People also ask

Does Python use getters and setters?

Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.

How do you declare a dictionary in the classroom?

You declare a dictionary with a set of curly braces, {} . Inside the curly braces you have a key-value pair. Keys are separated from their associated values with colon, : .

How do you initialize a new dictionary?

Initialization. Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

What are getter and setter methods Python?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.


1 Answers

Use an indexer property (MSDN):

public class YourClass {     private readonly IDictionary<string, string> _yourDictionary = new Dictionary<string, string>();      public string this[string key]     {         // returns value if exists         get { return _yourDictionary[key]; }          // updates if exists, adds if doesn't exist         set { _yourDictionary[key] = value; }     } } 

Then use like:

var test = new YourClass(); test["Item1"] = "Value1"; 
like image 160
James Michael Hare Avatar answered Sep 19 '22 17:09

James Michael Hare