Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading