Is there a difference between having a private setter or just defining a getter?

I need to create a class that combines two dictionaries together so that their values ​​can be obtained by key from the string int or .

Properties seems to be the best approach here, but is there a difference between the two implementations?

public class Atlas<TValue> { private Dictionary<int, TValue> _byIndex; private Dictionary<string, TValue> _byName; public Dictionary<int, TValue> ByIndex { get { return _byIndex; } } public Dictionary<string, TValue> ByName { get { return _byName; } } } 

and

 public class Atlas<TValue> { public Dictionary<int, TValue> ByIndex { get; private set; } public Dictionary<string, TValue> ByName { get; private set; } } 

In any case, the dictionary object is immutable, and the elements can be freely changed, which is what I want. However, an attempt to modify the dictionary object will either result in ~ cannot be assigned to -- it is read only , or ~ cannot be used in this context because the set accessor is inaccessible . I understand that the compiler will confuse my auto properties into something similar to the top block of code anyway ...

Actually, what compiler error is occurring?

+6
source share
1 answer

The only difference is that in the second case the setter is unavailable, but it is there, while in the first case there is no access. This means that a program that uses reflection can potentially access the properties of the second example, while in the case of the first example, you will need to access the fields.

As for non-reflective use, there is no difference between two pieces of code: external classes will not be able to install dictionaries.

You can go further and hide the presence of dictionaries from users of your classes. Instead of providing two properties of the Dictionary type, you can hide this implementation detail from users of your class by hiding it in a couple of methods:

 public class Atlas<TValue> { public bool TryGetByIndex(int index, out TValue val); public void Add(int index, TValue val); public bool TryGetByName(string name, out TValue val); public void Add(string name, TValue val); public TValue this[string name] { get ... set ...} public TValue this[int index] { get ... set ...} // You may want to add more methods or properties here, for example to iterate atlas elements } 
+4
source

Source: https://habr.com/ru/post/976593/


All Articles