How can I clone a DateTime object in C#?
A copy of DateTime object is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties.
Even if it would be a reference type, which it is not, it would still be passed by value. DateTime is a struct, so is not passed by reference - unless someone changed C# without telling me? You are incorrect, DateTime is a struct and therefore passed by value.
DateTime is a Value Type like int, double etc. so there is no way to assign a null value. When a type can be assigned null it is called nullable, that means the type has no value. All Reference Types are nullable by default, e.g. String, and all ValueTypes are not, e.g. Int32.
DateTime is a value type (struct
)
This means that the following creates a copy:
DateTime toBeClonedDateTime = DateTime.Now; DateTime cloned = toBeClonedDateTime;
You can also safely do things like:
var dateReference = new DateTime(2018, 7, 29); for (var h = 0; h < 24; h++) { for (var m = 0; m < 60; m++) { var myDateTime = dateReference.AddHours(h).AddMinutes(m); Console.WriteLine("Now at " + myDateTime.ToShortDateString() + " " + myDateTime.ToShortTimeString()); } }
Note how in the last example myDateTime
gets declared anew in each cycle; if dateReference
had been affected by AddHours()
or AddMinutes()
, myDateTime
would've wandered off really fast – but it doesn't, because dateReference
stays put:
Now at 2018-07-29 0:00 Now at 2018-07-29 0:01 Now at 2018-07-29 0:02 Now at 2018-07-29 0:03 Now at 2018-07-29 0:04 Now at 2018-07-29 0:05 Now at 2018-07-29 0:06 Now at 2018-07-29 0:07 Now at 2018-07-29 0:08 Now at 2018-07-29 0:09 ... Now at 2018-07-29 23:55 Now at 2018-07-29 23:56 Now at 2018-07-29 23:57 Now at 2018-07-29 23:58 Now at 2018-07-29 23:59
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With