Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clone a DateTime object in C#?

Tags:

c#

clone

datetime

How can I clone a DateTime object in C#?

like image 360
Iain Avatar asked Nov 24 '10 09:11

Iain


People also ask

How do I copy a DateTime object?

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.

Is DateTime passed by reference?

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.

Is DateTime a value type C#?

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.


1 Answers

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 
like image 168
Pieter van Ginkel Avatar answered Sep 18 '22 08:09

Pieter van Ginkel