User134932
User134932

Reputation: 13

What am I missing about reference types in this example?

I have the following code in that I create an object and pass it along through a series of forms to a user control.

public class MyObject
{
   public List<AnObject> Objects {get; set;}
}

Form 1:

private void MyObject _myObject = new MyObject{Objects = new List<AnObject>()};

...

Form2 form2 = new Form2(ref _myObject);
form2.Show();

Form 2:

public Form2(ref MyObject myObject)
{
    UserControl1 myControl = new UserControl1();
    myControl.Objects = myObjects.Objects
}

UserControl1

public List<AnObject> Objects {get; set;}
...

Objects.Add(new myObject());

When I Add a new myObject() to Objects in UserControl1, it doesn't update my original list on Form1. I am passing myObject by reference. The only thing I can think of that would be somehow unboxing my values is when I assign the list of AnObject to Form 2 to the UserControl1. What am I doing wrong?

Upvotes: 0

Views: 116

Answers (3)

The Smallest
The Smallest

Reputation: 5773

  1. ref has nothing with this example. Without ref you will pass reference of your list, just as you intended (and it would be shared by both forms). (Code where ref keyword is needed - is really rare code.)

  2. List<T> has no notification about its changes. So when you change its contents in one form, the other one doesn't know about it. Consider using ObservableCollection<T> and subscribe to its CollectionChanged event in your controls.

Upvotes: 4

Donnie
Donnie

Reputation: 46913

Objects in .NET are reference types anyways. ref in this case is only necessary if you might want to pass a different object back out in the same parameter instead of returning a new object. For what you're doing here, ref is completely unnecessary. (Contrast this with structs, which are value types, and so ref does something more potentially useful) Similarly, since Objects are already value types, there is no concept of boxing or unboxing here.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273199

The ref shouldn't even be necessary.

When I Add a new myObject() to Objects in UserControl1, it doesn't update my original list on Form1

It should have done that. Better post the exact code, this part shows me the code was not copy/pasted:

public Form2(ref MyObject myObject)
{
    UserControl1 myControl = new UserControl1();
    myControl.Objects = myObjects.Objects  // extra 's'
}

So we are now looking for a small problem in code that is an inexact copy of the real stuff. Hopeless.

Upvotes: 2

Related Questions