Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

DateTime is immutable

0.00/5 (No votes)
24 Oct 2012 1  
DateTime is immutable

In this post I am going to discuss about the DateTime object and how its immutable. But before I start its better to clear "What is immutable object in OOP" and "What is mutable object in OOP".
 

Immutable object

Object values cannot be modified once get created.

 
Mutable object

Object values can be modified or changed after get created.
 

So above definition clears the difference between mutable and immutable object in OOP.
 

Now coming on DateTime object following example shows how its immutable object.

//Create DateTime object 
DateTime dt = DateTime.Now;
//Now make change in object 
dt.AddDays(3);
//Write down dt 
Console.Writeln(dt);

When you run the above line and print value of the datetime variable on console. It write down current date rather than adding 3 day in it.

For example : -

if the current date is 26/3/2012 output is 26/3/2012 not 29/3/2012.

This example clear out that DateTime is immutable type. what ever you changes done by you its not change the value of datetime. If you want to make chnage in the value of DateTime variable value you need to write down

//Create DateTime object 
DateTime dt = DateTime.Now;
//Now make change in object 
dt = dt.AddDays(3);//change in above code
//Write down dt 
Console.Writeln(dt);

As you se above I did change in code by assigin value changed value to dt again so its now going to preserve the value what we change. Now if you write down value of dt on console its write donw "29/3/2012" if the current date is "26/3/2012".

I hope that I clear out the point DateTime is immutable because there are not of begineer level devloper thinks that when the do change in DateTime object it going to reflect on the sate of object.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here