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?
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.
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, : .
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 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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With