0

I'm new to C# and WPF, so please don't roast me to hard :)

I have an ObservableCollection<> of many objects which I show in a ListBox by using

MyListBox.ItemsSource = MyObservableCollection;

The goal now is to change the selected item, so what I'm doing is the following:

MyClass selectedObject = MyListBox.SelectedItem as MyClass;

Now I can just say something like selectedObject.Name = "Something" and of cause the value of selectedObject.Name gets changed. But to my surprise the value gets also changed in my original ObservabalCollection object ("MyObservableCollection").

This is exactly what I want, but tbh I don't understand why and how this works. How is selectedObject connected to the original object inside the ObservableCollection?

Further on im passing selectedObject as an argument to a new window, for doing the editing inside this new window:

EditObject editObject = new EditObject(selectedObject);

Even in the new window I can just asign new values to selectedObject and they get changed in my ObservableCollection too.

Can someone explain this behavior to me? :)

Thank you!

Baconman
  • 23
  • 3
  • 2
    As the name implies, `SelectedItem` holds a reference to the *selected item*, i.e. the element from the `ItemsSource` collection that is currently selected. – Clemens Oct 09 '18 at 13:01
  • I suggest reading this, or any post you find about value and reference types: https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value/430958#430958 – Igor Meszaros Oct 09 '18 at 13:06
  • Thank you, I see the point now! – Baconman Oct 09 '18 at 13:09
  • I don't understand the down vote, I think as a new learner when you have no idea why certain things are happening and certain concepts exist. It's difficult to google for something you don't know exist. – Igor Meszaros Oct 09 '18 at 13:10

1 Answers1

0

MyListBox.SelectedItem is a reference to the object in your observable collection. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

If you pass the reference of this object to another window and modify it there it should also change in the original ObservableCollection.

int for instance is not a reference type and will pass by value. It won't change in the original location.

Try this example:

class Program
{
    static void Main(string[] args)
    {
        TestClass testClass = new TestClass();
        Console.WriteLine(testClass.number);
        ChangeTest(testClass);
        Console.WriteLine(testClass.number);

        int i = 0;
        Console.WriteLine(i);
        ChangeInt(i);
        Console.WriteLine(i);


        Console.ReadKey();
    }

    public static void ChangeTest(TestClass t)
    {
        t.number++;
    }

    public static void ChangeInt(int i)
    {
        i++;
    }
}



public class TestClass
{
    public int number = 0;
}

Will give you this output:

0
1
0
0
fstam
  • 669
  • 4
  • 20