-3

Supose that I have this:

CustomObject myCO1 = new CustomObject();
CustomObject myCO2 = myCO1;
CustomObject myCO3 = new CustomObject();
myCO1 = myCO3;

I would like that myCO2 has the same reference than myCO1, to myCO3. Is there any way to do that?

Thank so much.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    why would you even want to do that if you could just work with one reference? – BoeseB Feb 03 '15 at 12:07
  • I am thinking o a dialog, I would like to have a result variable that when is modifing on the dialog, the result is "transmitted" to the view model that calls the dialog. – Álvaro García Feb 03 '15 at 12:09
  • @ÁlvaroGarcía For this kind of scenario you should probably try a different approach. You could either expose a `Result` property on the dialog which your view model can bind to, or try sending a wrapper object to the dialog which holds the result as a property instead. – odyss-jii Feb 03 '15 at 12:13
  • so you are looking for the ref keyword in a method call? https://msdn.microsoft.com/en-us/library/14akc2c7.aspx – BoeseB Feb 03 '15 at 12:14

2 Answers2

4

No, assigning a new reference just copies the reference value into the new variable. When you change it's reference the other variables that references the same place are not affected.

So in your case, myCO2 references the old location of myCO1. And myCO1 and myCO3 are referencing to same location.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

It sounds a little bit like you could use a primer on references and values in C#. Specifically: "If x is a variable and its type is a reference type, then changing the value of x is not the same as changing the data in the object which the value of x refers to"

However, let me edit your example for a bit of clarity:-

CustomObject myCO1 = new CustomObject("A");
CustomObject myCO2 = myCO1;
CustomObject myCO3 = new CustomObject("B");
myCO1 = myCO3;

You can see clearly that myCO2 refers to "A", even after you change myCO1 to refer to "B". This is because while a reference refers to another object, it is itself a value.

There are largely two ways you can achieve the outcome you desire.

The first option is using a reference type (rather than a value) to refer to your CustomObject:-

public sealed class Reference<T>
{
  public T Value { get; set; }
}

...

Reference<CustomObject> myCO1 = new Reference<CustomObject>()
                                {
                                  Value = new CustomObject("A");
                                };
Reference<CustomObject> myCO2 = myCO1;

CustomObject myCO3 = new CustomObject("B");
myCO1.Value = myCO3;

The second option you have is to encapsulate the logic you require in a method and use the ref keyword

Community
  • 1
  • 1
Iain Galloway
  • 18,669
  • 6
  • 52
  • 73