Limit the Write Access of a Value to Other Classes Only #4507
-
In C# the "public" keyword exposes a type or member to other classes while "private" hides it to all classes but itself. But what if I wanted to restrict write access for a value such that only other classes can assign to it? Example use case:Problem: // The default value for the counter.
private const int s_DefaultCount = 10;
// A counter that can only decrement through use of the property but the local class has its own logic for the backing field.
private int m_Counter;
public int Counter {
get {
return m_Counter;
}
set {
if (value < m_Counter) {
m_Counter = value;
}
}
}
private void ResetCounter() {
Counter = s_DefaultCount; // Oops. Well, this bug is easy to see. But imagine this in a larger block of code!
} Solution: // The default value for the counter.
private const int s_DefaultCount = 10;
// Write access to the auto property is restricted to other classes only!
private int m_Counter;
public only int Counter {
get {
return m_Counter;
}
set {
if (value < m_Counter) {
m_Counter = value;
}
}
}
private void ResetCounter() {
m_Counter = s_DefaultCount // Correct usage. No bugs here!
int someInt = Counter // Allowed because we still have read access just not write access.
Counter = s_DefaultCount; // Inaccessible due to its protection level. No more accidental bugs!
} This is just one simple example but this type of access modifier would be extremely useful:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
C# has relatively few accessibilities. Each additional accessibility massively increases complexity - not just for the compiler but for analysers and source generators as well (I have spent many hours wrangling with accessibility in StrongInject, before eventually resorting to a less than perfect solution). I don't think I've ever needed this particular accessibility. Given how niche it is, I think it quite unlikely that it justifies the costs. |
Beta Was this translation helpful? Give feedback.
C# has relatively few accessibilities. Each additional accessibility massively increases complexity - not just for the compiler but for analysers and source generators as well (I have spent many hours wrangling with accessibility in StrongInject, before eventually resorting to a less than perfect solution).
I don't think I've ever needed this particular accessibility. Given how niche it is, I think it quite unlikely that it justifies the costs.