0

Why .Net DateTime properties cannot be assigned to? It would be useful to be able to do things like:

DateTime saveNow = DateTime.Now;
saveNow.Second = 0; //Error, it does not compile
svick
  • 236,525
  • 50
  • 385
  • 514
G. Lari
  • 435
  • 2
  • 14
  • 6
    Mutable value types are evil. – SLaks Jun 10 '13 at 15:49
  • 1
    If I understand correctly you're saying that: DateTime is a struct (not a class) and mutable struct are bad practice. That's why they are, by design, not mutable. – G. Lari Jun 11 '13 at 12:39

3 Answers3

1

Because they are accessor properties, thus read only.

DateTime now = DateTime.Now;
DateTime saveNow 
   = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • Yes, but I wanted to know why DateTime has only Get accessor and not Set accessor. @SLaks answered shortly to it. Thank you for the code, it's the way I solved my problem. And now I more sure it is the correct way to go. – G. Lari Jun 11 '13 at 12:48
  • @user511956 - Please mark it as the answer then, since it solved your problem – Gabe Jun 12 '13 at 13:47
1

try this:

DateTime saveNow = DateTime.Now;

saveNow.AddSeconds(-savenow.Second); AddSeconds doesn't change the value, it returns a new instance with the new value. This version works:

saveNow = saveNow.AddSeconds(-savenow.Second);
0

I summarize what @SLaks and @Gabe said:

DateTime is a struct (not a class) and mutable struct are bad practice. Check here for details Why are mutable structs evil?

Because of this, DateTime is by design not mutable.

To set the DateTime 'seconds' field to 0 you can use this code:

DateTime now = DateTime.Now;
DateTime saveNow 
 = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
Community
  • 1
  • 1
G. Lari
  • 435
  • 2
  • 14