A little back story here. I’ve got a public property (typeof(ObservableCollection<Area>)) that I bind a treeview to. I’d like to update the tree, but I don’t want to redraw the whole thing and lose the selected item, collapsed/expanded states of nodes and anything else I forget to implement. So I think I need to update the Area within the collection. I notice that using a FirstOrDefault statement and setting it equal to something does not actually change the Area in the observable collection:
var areas = GetAreaInfo(); //Entity Framework query returns ObservableCollection<Area>
foreach (Area a in areas)
{
var αrea = Areas.FirstOrDefault(α => α.Id == a.Id);
if (αrea != null)
αrea = a; //αrea changes, but Area[0] which is supposed to be αrea doesn't
}
Can I get a reference or pointer to the object so I don’t have to iterate through the observable collection and use indexes?
You’re not actually doing what you think you’re doing. In your case, area is just a variable. When you set area = a, you’re resetting the location that the ‘area’ variable is pointing to, not changing the observable collection at all.
Your best bet is to update all of the properties of area to match the properties of a. It’s usually easy enough to write a Clone or Copy method to copy the properties from one instance of the object onto another instance. Your other option is to remove area from the collection and add a instead, but that is likely to cause some problems with ordering.
EDIT: And on your actual question, yes, it’s possible to get pointers in C#, but it’s a bad idea. It will take a lot more work to write, requires you to mark you code as unsafe, and will be more difficult to maintain going forward.