- Home /
Getter and Setter in C#
I've got this in one class (which is then initialized in the constructor):
public Dictionary<int, List<Obj>> objectsBySystem { get; private set; }
My hope was that this restricts the variable to the internal scope only, such that values cannot be set from outside the class.
Unfortunately, testing this from an outside class, it seems that these values can still be set:
print(ObjectManager.instance.objectsBySystem.ContainsKey(123));
//yields False
ObjectManager.instance.objectsBySystem.Add(123, new List<Obj>());
print(ObjectManager.instance.objectsBySystem.ContainsKey(123));
//yields True
Any advice? Thanks!
Answer by steakpinball · Dec 30, 2013 at 02:59 AM
Specifying private set;
only makes setting the dictionary itself to private. You can not do
ObjectManager.instance.objectsBySystem = new Dictionary<int, List<Obj>>();
outside of the class.
If you want to limit calling of methods you should make objectsBySystem
private.
private Dictionary<int, List<Obj>> objectsBySystem;
A basic solution provides intermediate methods for funtionality you want to access. An example would be a basic getter.
public List<Obj> GetObjectsBySystemNumber(int number)
{
return objectsBySystem[number];
}
You also have the option of using an indexer for basic getting and setting of values instead of methods. http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
public List<Obj> this[int number]
{
get { return objectsBySystem[number]; }
private set { objectsBySystem[number] = value; }
}
the indexing part was new to me, that's quite interesting. thanks
Answer by KellyThomas · Dec 30, 2013 at 03:00 AM
This:
ObjectManager.instance.objectsBySystem.Add(123, new List<Obj>());
Is equivalent to:
List<Obj> list = ObjectManager.instance.objectsBySystem;
list.Add(123, new List<Obj>())
so you are only using the getter, however the Dictionary is mutable and as such changes can be made once it is handed to the other class.
Microsoft have some support for an `ImmutableDictionary` but it is at .NET 4.5 and not available for unity.
Depending on the properties of a Dictionary you value most you could implement a class that takes a copy of the key/value pairs and stores them as parallel ImmutableList
s this would allow you to implement data look up but would not have the speed of a true hashmap.
The easiest (and probably fastest to execute) would be to encapsulate the Dictionary
and provides accessor methods for the functionality you want to reveal.
private Dictionary<int, List<Obj>> objectsBySystem = new Dictionary<int, List<Obj>> ();
public bool ObjectsContainsKey(int key) {
return objectsBySystem.ContainsKey(key);
}
public List<Obj> ObjectsGetValue(int key) {
return objectsBySystem[key];
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613125123im_/https://answers.unity.com/themes/thub/images/avi.jpg)