C# - variable modifiable from only one method

86 views Asked by At

Is there a way to have a variable avaliable for reading from anywhere but modifiable from only one method in a class?

For example

public class ClassA
{
    public int IntegerA;

    public ClassA(){}

    public void MethodA()
    {
        //should work in this method
        IntegerA=100;
    }

    public void MethodB()
    {
        //shouldn't work here
        IntegerA=100;
    }
}

public class ClassB
{
    public void MethodC()
    {
        ClassA classA = new ClassA();

        //should be readable
        int b=classA.IntegerA;

        //modifying shouldn't work here as well
        classA.IntegerA=100;
    }
}

I tried creating additional class containing only IntegerA and MethodA and it kinda works but MethodA also uses some private variables from ClassA so it would be better to make it all one class.

1

There are 1 answers

0
abolfazl  sadeghi On

If you want the variable to be changed only by one method, you must make a class of abstract(BaseClass) type and the main class will inherit from it.

public abstract class BaseClass
    {
        public int IntegerA { get; private set; }
        public BaseClass() { }

        public void MethodA()
        {
            //should work in this method
            IntegerA = 100;  
        }
    }

ClassA


 public class ClassA : BaseClass
    {
        public ClassA() { }
        public void MethodB()
        {
            //should work in this method
            var b = IntegerA;
            //shouldn't work here
            IntegerA = 10;//error
        }
    }

If you want the variable to be changed only by methods inside class, you must change access type , can read inside or outside class this variable

 public int IntegerA { get; private set; }