Hello
If I create a DateTime instance like this :
DateTime d=DateTime.Now();
And then
d.AddDays(3);
The 3 days doesnt get added to it. But If I do like this :
DateTime d=DateTime.Now.AddDays(4);
The days gets added correctly.
Can anyone explain me the behaviour ??
Madhur
Larry Lard - 05 Jul 2006 11:31 GMT
> Hello
>
[quoted text clipped - 10 lines]
>
> Can anyone explain me the behaviour ??
.AddDays is a _function_ that returns the _new_ value, not a method
that changes the existing value. Thus when you do
d.AddDays(3);
you are saying: Take the value of d, add three days to it, then do
nothing with the result. The three days does get added to it; but the
result is then thrown away.
But when you say
d=DateTime.Now.AddDays(4);
you are saying: Take the value of DateTime.Now, add four days to it,
and _assign the resulting value to d_.
If you want to change d from its current value to (its current value
plus three days), you should say
d = d.AddDays(3);

Signature
Larry Lard
Replies to group please
ValliM - 05 Jul 2006 12:04 GMT
Hi Madhur,
You have added 3 days to d, but you did not store the value to any variable.
So as intialized in the first step d has the present time alone.
Moreover you have used DateTime.Now(), Now is the property but it is used
like a method.
This might work correctly.
DateTime d = DateTime.Now;
d=d.AddDays(3);
Regards,
Valli.
www.syncfusion.com
> Hello
>
[quoted text clipped - 12 lines]
>
> Madhur
Jon Skeet [C# MVP] - 05 Jul 2006 19:17 GMT
> If I create a DateTime instance like this :
> DateTime d=DateTime.Now();
[quoted text clipped - 8 lines]
>
> Can anyone explain me the behaviour ??
Whenever something surprising happens, it's best to consult the
documentation. Here's part of what MSDN says about DateTime.AddDays in
the "Remarks" section:
<quote>
This method does not change the value of this DateTime. Instead, a new
DateTime is returned whose value is the result of this operation.
</quote>

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Madhur - 05 Jul 2006 19:45 GMT
>> If I create a DateTime instance like this :
>> DateTime d=DateTime.Now();
[quoted text clipped - 17 lines]
> DateTime is returned whose value is the result of this operation.
> </quote>
Thanks to all those who replied. Indeed I should have consulted the
documentation first.
--
Madhur Ahuja