Wednesday, May 12, 2010

What's in a name? .NET Framework naming gotchas

I saw a question in Stackoverflow

I was recently working with a DateTime object, and wrote something like this:

DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date!

The intellisense documentation for AddDays says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like:

DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date


I think AddDays should be named NextDays. dt.NextDays(1) doesn't have a notion that it changes its own value, in the same vein that data structure constructs, e.g. node->next, node.next, doesn't modify the value of node. And.. it's too late now, they could give dt.AddDays the semantics that it add days to its own value

No comments:

Post a Comment