Search code examples
c#objectreferenceparameter-passingref

C# ref weird behaviour


I recently had a strange experience with C# refs.

Please take a look at this code:

class Program
{
    public static bool testBool = true;
    public static RefClass RefObject;
    public static int X = 0;

    static void Main(string[] args)
    {
        while (true)
        {
            
            if (testBool)
            {
                RefObject = new RefClass(ref X);
                testBool = false;
            }

            X++;
            Thread.Sleep(200);
            Debug.WriteLine(X);
            Debug.WriteLine(RefObject.X);
        }
    }

    public class RefClass
    {
        public int X { get; set; }
        public RefClass(ref int x)
        {
            X = x;
        }
    }
}

I still can't figure out why the property X of RefObject doesn't update with the variable X. Isn't ref supposed to be a reference to the original variable? That would mean that X (property of RefObject) should be only a reference to the static X variable, which is supposed to result it them being the same.


Solution

  • Let's look at the constructor:

    public RefClass(ref int x)
    {
        X = x;
    }
    

    Specifically this line:

    X = x;
    

    At this point, the lower-case x variable IS a ref variable. However, when you copy it to the upper-case X property, you are still copying it's value at that time to the property. The X property is still just a regular integer, and as far as I know there is no way to declare a reference property in the way you want.