Reputation: 22652
I have following code for AddTicks
method. Ticks property of datetime object is returning same value before and after the AddTick method. Why is it behaving so?
There are 10,000 ticks in a millisecond.
Ticks: The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.
AddTicks : Adds the specified number of ticks to the value of this instance.
Note: I am using .Net 4.0
framework
CODE
static void Main()
{
DateTime dt2 = new DateTime(2010, 5, 7, 10, 11, 12, 222);
long x = dt2.Ticks;
dt2.AddTicks(9999);
long y = dt2.Ticks;
bool isSame = false;
if (x == y)
{
isSame = true;
}
Console.WriteLine(isSame);
System.Console.ReadKey();
}
Upvotes: 6
Views: 5142
Reputation: 15076
AddTicks
(and the other Add*
methods) does not alter the DateTime, but returns a new object.
So you should use
dt2 = dt2.AddTicks(...)
DateTime
is a value type and is immutable.
Upvotes: 21
Reputation: 4546
DateTime values (like strings) are immutable.
Any operation on a DateTime instance won't change the value of that instance, but instead will return a new DateTime value that you have to capture.
dt2 = dt2.AddTicks(9999);
Upvotes: 3