I was writing a method which takes DateTime value as one of it’s parameters. I decided that it’s optional parameter so I went ahead and tried to make DateTime.MinValue as default.
private void test(string something, DateTime testVar = DateTime.MinValue) {
}
However this gives an error that:
Default parameter value for ‘testVar’ must be a compile-time constant.
Using this code seems to work just fine.
private void test(string something, DateTime testVar = new DateTime()) {
}
I was given advice to use DateTime.MinValue instead of new DateTime() as it’s self-documenting. Since new DateTime() is basically the same thing why DateTime.MinValue can’t be used? Also will there be any potential problem if I leave it with new DateTime()?
DateTime.MinValueis defined as:Which is not the same as
const. Since areadonlyvalue is not a compile-time constant (i.e. the value is not evaluated at compile-time), it can’t be used.The reason that using
new DateTime()works is because that expression is known at compile-time. It’s the same as writingdefault(DateTime). For example,result == truein the following expression: