Search code examples
c#oopreadonlyaccess-modifiers

Variable read only


I have a problem with changing a variable from different class. Even tho I used access modifiers (get and set), compiler still sees it as read only, and I cannot change it within another class.

private float speed;

public float Speed
{
    get {return speed;}
    set {speed = value;}
}

I'm not sure if this matters, but this variable is from my main, abstract class and I use it in other classes. What is happening here, is that I assigned value to this variable in one class (Player.cs) and I'm trying to change it in another class by initializing its object (Physics.cs). They are both inheriting from that main, abstract class.


Solution

  • If you're only setting speed once, just use a readonly variable and set it in the constructor:

    public class Physics
    {
        private readonly float speed;
    
        public Physics()
        {
            this.speed = 5;
        }
    }
    

    You can set a readonly variable exactly once.

    If you really do need to change speed within the lifetime of your object, just use an auto property anyways for simplicity:

    public float Speed {get; set;}