-2

I have this code below where I fetch a object 'yogaSpaceEvent' from the DB as a entity. I want to save the values before I modify anything and then pass the old values (as a object) and the object with the newly saved values to another method 'getEditedEventEmail' to do some logic. But the 'oldEvent' object has all the new values of 'newEvent'.

YogaSpaceEvent yogaSpaceEvent = yogaSpace.YogaSpaceEvents.Where(k => k.YogaSpaceEventId == details.EventId).First();

            if (yogaSpaceEvent == null)
                throw new Exception("You Don't Have A Yoga Space Event With This ID!");

            YogaSpaceEvent oldEvent = yogaSpaceEvent; // save all the old values in this object

            var displayedTime = details.StartTime.GetType().GetMember(details.StartTime.ToString()).First().GetCustomAttribute<DisplayAttribute>().Name;
            yogaSpaceEvent.EventDateTime = details.EventDate.AddHours(DateTime.Parse(displayedTime).Hour).AddMinutes(DateTime.Parse(displayedTime).Minute);
            yogaSpaceEvent.Time = details.StartTime;
            yogaSpaceEvent.Duration = details.Duration;
            yogaSpaceEvent.Style = details.Style;
            yogaSpaceEvent.DateUpdated = DateTime.Now;

            YogaSpaceEvent newEvent = yogaSpaceEvent; // save all the new values in this object to compare with the old object

            Tuple<string, string> editedEventEmail = _emailingService.GetEditedEventEmail(oldEvent, newEvent);
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 1
    I think you need to revisit the core language features of C#. The values of `oldEvent`, `yogaSpaceEvent` and `newEvent` will just be references to the same object. See http://jonskeet.uk/csharp/references.html – Jon Skeet Jan 23 '17 at 22:02
  • Possible duplicate of [How do you do a deep copy an object in .Net (C# specifically)?](http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically) – Fruchtzwerg Jan 23 '17 at 22:04

2 Answers2

1

Assuming YogaSpaceEvent is a reference type:

 YogaSpaceEvent oldEvent = yogaSpaceEvent; 

Just copies off the reference. Both references still point to the same object. If after that line you had written:

yogaSpaceEvent = new YogaSpaceEvent();

Then you would get the behavior you are looking for as the two variables would be pointing at different objects. You can also do a "deep copy" into oldevent but the techniques for doing so in the general case are a bit more involved (for simple cases, MemberwiseClone is fine).

The general case of deep copying is is discussed further in: How do you do a deep copy of an object in .NET (C# specifically)?

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
0

Please test this:

YogaSpaceEvent oldEvent = new YogaSpaceEvent{
  property1 = yogaSpaceEvent.property1,
  property2 = yogaSpaceEvent.property2,
  .
  .
  .
  };
Farzin Kanzi
  • 3,380
  • 2
  • 21
  • 23