Search code examples
c#refvalue-type

Assign value of a reference property to a variable


I have a scenario where I want to pass in a reference of the value type bool (value type marked with ref) to a constructor of an other class and want to update its value in the other class. Something like this. Is there a way to hold the reference of the variable. (I marked things with public, and I know that public variables can be accessed from anywhere)

public class A
{
    public bool Update;
    public void DoSomething()
    {
        B b = new B(ref Update);
    }
}

public class B
{
    private ref bool _val; //Is it possible to create a variable like this. If not is there a way to achieve what I am doing.
    public B(ref bool value)
    {
        _val = value;
    }
    private void UpdateValue()
    {
        _val = true;
    }
}

Solution

  • Wrap value with the reference type

    public class CanUpdate
    {
        public bool Value { get; set; }
    }
    

    Then

    public class B
    {
        private readonly CanUpdate _canUpdate;
    
        public B(CanUpdate value)
        {
            _canUpdate = value;
        }
    
        private void UpdateValue()
        {
            _canUpdate.Value = true;
        }
    }
    

    Class A will "see" value changed by class B

    public class A
    {
        private CanUpdate CanUpdate;
    
        public A()
        {
            CanUpdate = new CanUpdate { Value = false };
        }
    
        public void DoSomething()
        {
            Console.WriteLine(CanUpdate.Value); // false
    
            var b = new B(CanUpdate);
            b.UpdateValue();
    
            Console.WriteLine(CanUpdate.Value); // true
        }
    }
    

    Having own dedicated type for a value improves readability and makes code more comprehensible for others.