views:

77

answers:

3

Here's my code:

        Event thisEvent = (from i in list
                           where (i.eventID == eventID)
                           select i).FirstOrDefault();
        if (thisEvent != null)
        {
            thisEvent.eventResolved = resolved;
            thisEvent.eventSequence.Add(item);
        }

"list" is a collection of IEnumerable, i.e.

IEnumerable<Event> list;

What I'm wondering is: after creating thisEvent using FirstOrDefault, is thisEvent still connected to list? In other words, when I change the two properties, eventResolved and eventSequence, is "list" actually changed, or is thisEvent just some totally disconnected copy of an item in "list"?

+4  A: 

FirstOrDefault selects an item in a collection, but does not "detatch" or "clone" it. I.e. it is the same instance. So if you modify a property you modify the original instance.

If you want to "detatch" the object you will have to copy it in some way or the other.

Obalix
Thanks! (blah de blah blah to get to 15 characters ...)
Cynthia
Cynthia couldn't upvote you (3 rep). I'm doing this for her =).
Samuel Carrijo
A: 

list is not changed, and still includes the object returned by FirstOrDefault.

This is a general rule with all the LINQ operators: they never modify the source collection.

Also note that thisEvent is not a "copy" (unless Event is a value type (struct) rather than a class) -- it is a reference to the same object that is referenced in list.

itowlson
Hmmmm ... but if it's a reference to the same object, then the list would be changed, would it not? At least, in terms of that object -- not in terms of some element having been added or removed from the list.
Cynthia
The *list* is not changed. The same objects are still in the list after calling FirstOrDefault(). But yes, it it possible to modify a list *element* via the returned reference (again, assuming Event is a class rather than a struct). This is a characteristic of .NET references, not anything inherent to lists or FirstOrDefault: similarly, if you wrote `Event thatEvent = thisEvent;`, then changes made to the object through the `thatEvent` reference would also be seen through the `thisEvent` reference. One object, multiple references.
itowlson
A: 

If Event is a reference type, then yes, modifying thisEvent will modify the element in the list.

Darin Dimitrov