2

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?

4
  • Objects are inherently pointers in C#. Commented Jul 23, 2012 at 13:33
  • 8
    Using α for a lambda is fine but if you use area and αrea in my code base, prepare for nightmares. Yes, this is a threat. Commented Jul 23, 2012 at 13:42
  • @James, how is that comment helpful? Does it affect me and my problem here? Thanks Commented Jul 26, 2012 at 12:37
  • @KonradRudolph ...Welcome to the thunderdome! I admit I should have changed that before posting. The alpha was keeping me amused during my moment of frustration and wasn't meant to be permanent. Commented Jul 26, 2012 at 12:39

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aye, that's what I noticed when debugging the code. Also, I thought pointers were only allowed for basic types or structs contain basic types per msdn.microsoft.com/en-us/library/y31yhkeb(v=vs.80).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.