John Tan
John Tan

Reputation: 1385

Passing with ref keyword

I have 2 tab pages (tabA and tabB) within a main form. Say I pass tabA into tabB at the main form initalization:

tabB = new TabB(tabA);

So what i observe is that after changing a value inside tabA (say tabA.Text) , the value inside tabB (tabB.tabA.Text) changes as well.

So my understanding (from C++) is that this is similar to pass-by-reference. So my question is what is the difference if I write this instead?

tabB = new TabB(ref tabA);

Upvotes: 1

Views: 73

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Your analogy to C++ is incorrect. Passing reference objects* in C# is similar to passing objects by pointer in C++, with the exception that C# does not require an asterisk to dereference these pointers.

Passing by reference in C# would be similar to passing a pointer by reference in C++: in addition to using that pointer inside your function, you would also be able to assign a new value to it, thus changing the value of the pointer in the caller.

Here is a short illustration:

void One(List<int> list) {
    // Reassignment of the list is local to method One
    list = new List<int> {1, 2, 3};
}
void Two(ref List<int> list) {
    // Reassignment of the list is visible in the caller
    list = new List<int> {1, 2, 3};
}
...
var demo = new List<int> {5, 6, 7};
One(demo);
// Here the list remains [5, 6, 7]
Two(ref demo);
// Here the list becomes [1, 2, 3]

* As opposed to value objects, such as structs and primitives, which are copied.

Upvotes: 3

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

The difference is that by using the ref keyword you can change the reference itself, not just the object being pointed to by the reference.

void funcA(TabA tabA)
{
   // setting tabA to null here has no effect outside this function
   tabA = null;
}

void funcB(ref TabA tabA)
{
   // setting tabA to null persists outside this function
   // and changes the actual reference passed in.
   tabA = null;
}

// tabA initialized to non-null
tabA = new TabA();

funcA(tabA);

// tabA is still not null

funcB(ref tabA);

// tabA is now null

Upvotes: 0

user35443
user35443

Reputation: 6413

The difference would be, that if you changed the object pointed to by tabA argument in TabB constructor, tabA would use the new object too.

There actually isn't a way to pass the object itself, but you may do a copy / clone, which would look just like the original. There has already been written a good answer for the general case of copying a windows control, and an answer for the tabs only.

Upvotes: 1

Related Questions