How to make a field read-only outside the class

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’s object, the number of teeth calculated must be calculated. I would like to have access to this value without being able to change 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 cannot figure out which access modifier will allow me to do this. I tried all of the following:

If I create numberOfTeeth private , I cannot access it.
If I create a numberOfTeeth protected internal , I can change this value outside the class.
If I create a numberOfTeeth internal , I can change this value outside the class.
If I create numberOfTeeth protected , I cannot access it.
If I numberOfTeeth public , I can change this value outside the class.

I also tried to make it readonly , but then could not install it outside the constructor.

Is there any access modifier that will allow me to do this? Or is there some other way to implement this protection?

+4
source share
4 answers

Create a property using a private setter:

 public int NumberOfTeeth { get; private set; } 

Please note: I changed it to Pascal Case to comply with most standards of the .NET standard.

+8
source

You cannot do this. You can make the field read-only and create a method that returns its value. You can also create an automatic property with an open getter and a secure network device:

 public int NumberOfTeeth { get; protected set; } 
+2
source
 public class Dog { public int numberOfTeeth { get; private set; } public Dog() { countTeeth(); } } 
0
source

You must create a private field and create a read-only public property (without a setter):

 public class Dog { private int numberOfTeeth; public int NumberOfTeeth {get {return numberOfTeeth;}} public Dog() { countTeeth(); } private void countTeeth() { this.numberOfTeeth = 5; //this dog has seen better days, apparently } } 
0
source

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


All Articles