-1

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.

Papouc
  • 25
  • 7
  • 2
    The idea is that if you assigned a new value to `x` in the constructor of `RefClass`, you could observe it, but you didn't. New assignments after the fact are not involved, and RefClass.X is not forever linked to your initial argument. – Anthony Pegram Dec 08 '21 at 20:14

1 Answers1

1

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    It is impossible because it would make RefClass hold a reference to something defined outside it's scope, literally meaning.... that you would... create a ton of problems with isolation down the road. Note how all uses of ref flow along a code path - having a ref variable would mean that the reference would exist outside of the code path. – TomTom Dec 08 '21 at 20:22
  • Thanks, I was just curious about the explenation! Thanks againg and have a nice day! – Papouc Dec 08 '21 at 20:58