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?
You can't do that. You can make the field read-only and make a method that returns its value. You can also make an auto-property with a public getter and a protected setter:
Create a property with a private setter:
Notice I changed it to Pascal Case to match most .NET style standards.
You should make the field
private
and create a read-only (no setter)public
property: