0

How can I change the value of passed reference variable by the other method's of the class. I have embedded the comments in the code snippet.

class A
    {
        int myVar = 0;
        void SomeMethodOfA ()
        {
            B obj = new B(ref myVar);
            Console.WriteLine(myVar);   // Need updated value of myVar
        }
    }

class B
{
    int newVar;   // Intentionally not initialised.
    public B()
    {
        //something
    }
    public B(ref int x) : this()
    {
        // Purpose is to change the value of 'x' by the other method's of this class.
        newVar = x; //This is not assigning newVar the reference of x
                    // What I am missing here...?
    }
    private void buttonSomething_Click(object sender, EventArgs e)
    {
        newVar++;   //This change in only local.
                    // I need this change to reflect in 'x'
    }
}
Koder101
  • 844
  • 15
  • 28
  • 2
    You can't. So encapsulate it in a class and stop passing it by ref. –  Mar 22 '17 at 14:54
  • @Will Instead of class, Can I do it with struct? – Koder101 Mar 22 '17 at 14:56
  • 2
    Yeah. But no. Really, structs should be immutable. Use a class. Now that I think about it, definitely no. Structs are passed by value, not reference, so the same issue applies. –  Mar 22 '17 at 14:57
  • Why are you trying to avoid using a class? – Luaan Mar 22 '17 at 14:59
  • @Luaan I am not avoiding using a class, I knew that class would do the job. However, since I came across this situation, so wanted to know if anything exists like that in C#. – Koder101 Mar 22 '17 at 15:03
  • 1
    Allowing arbitrary `ref` is tricky, since it allows you to leak references to objects all over the place. This would mean the garbage collector would need to keep track of all `ref`s everywhere in your application, completely negating most of the advantage of using `ref` in the first place. In its limited form, the lifetime of a `ref` is *always* tied to local function scope, which is trivial to manage. – Luaan Mar 22 '17 at 15:13

0 Answers0