0

I'm trying to create a program that outputs an itinerary, but I'm having issues with finding a way around my two DateTime objects pointing towards the same object. A specific DateTime is passed as an argument into the method and I use two other DateTime object within the method (which both currently point to the argument)

None of my normal fixes like memberwiseClone() work for DateTime, so I'm at a bit of a loss.

{
    DateTime1 = x;
    for (int i = 0; i < someArray.Length; i++)
    {
        DateTime2 = DateTime1;
        double minutes = someValue / someOtherValue;
        DateTime2.AddMinutes(minutes);
        WriteLine("{0:hh//:mm} ---> {1:hh//:mm}, item #{2}", DateTime1, DateTime2, i);
        DateTime1 = DateTime2;
    }
}

I would ideally like it to print out something along the lines of:

"21:00 ---> 21:30, item #1"
"21:30 ---> 22:00, item #2"

However, at the moment I'm just getting all values at the initial value of the DateTime argument.

Stoogy
  • 1,307
  • 3
  • 16
  • 34
KMD92
  • 41
  • 4
  • 5
    Not sure what you mean here, `DateTime` is a value type, which means it contains the value entirely, it does not reference a common object. Basically, in your code here you have 3 DateTime values, `x`, `DateTime1`, and `DateTime2`, these are separate. Changing one does not change another. Can you please clarify what the problem is? – Lasse V. Karlsen May 22 '19 at 08:17
  • Please familiarize with https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c – Renat May 22 '19 at 08:18
  • What output do you get instead of the desired output? – Chetan May 22 '19 at 08:23
  • 1
    Thanks for your help, an answer below gave me the fix. Don't know why I thought DateTime was an object instead of a value type, but guess that's all part of learning to code. – KMD92 May 22 '19 at 08:26

2 Answers2

1

System.DateTime struct is immutable which means it could not be changed. Its methods like AddMinutes are not changing the value of the original structure, but it has a return value that contains a value that is the result of the specified operation.

You should use DateTime2 = DateTime1.AddMinutes(minutes) instead.

Alsein
  • 4,268
  • 1
  • 15
  • 35
0

The line DateTime2.AddMinutes(minutes); is not void, it returns the result. Change it to:

DateTime2 = DateTime1.AddMinutes(minutes);
Rafael-WO
  • 1,434
  • 14
  • 24