How to make a field read only outside class
.net, access-modifiers, c#
Solution
Create a property with a private setter:
public int NumberOfTeeth
{
get; private set;
}
Notice I changed it to Pascal Case to match most .NET style standards.
Problem
I have the following class (example): ``` public class Dog { int numberOfTeeth; public Dog() { countTeeth(); } private void countTeeth() { this.numberOfTeeth = 5; //this dog has seen better days, apparently } } ``` After I create the dog object, it should have the number of teeth calculated. I'd like to be able to access that value without being able to modify it outside the class itself. ``` Dog d = new Dog(); int dogTeeth = d.numberOfTeeth; //this should be possible d.numberOfTeeth = 10; //this should not ``` However, I can't figure out which access modifier will let me do this. I've tried all of the following: If I make `numberOfTeeth` private, I cannot access it. If I make `numberOfTeeth` protected internal, I can change this value outside the class. If I make `numberOfTeeth` internal, I can change this value outside the class. If I make `numberOfTeeth` protected, I cannot access it. If I make `numberOfTeeth` public, I can change this value outside the class. I also tried making it readonly but then was unable to set it outside the constructor. Is there any access modifier which will allow me to do this? Or is there some other method of accomplishing this protection?