开发者

C# - Why are DateTime.MinValue and MaxValue not compile-time constants?

I wanted to have an optional date parameter for a method (defaulted to MinValue), in order to check if the user had actually supplied a value or not (supplying MinValue was invalid), but I'm not allowed as apparently it's not a compile-time constant.

According to the MSDN page, "The value of this constant is equivalent to 00:00:0开发者_JAVA技巧0.0000000, January 1, 0001."

So why is that not compile-time constant? And why is it different from passing in Int32.MinValue, which is allowed?


You cannot define a DateTime constant (or structs). From MSDN allowed types for const are:

One of the types: byte, char, short, int, long, float, double, decimal, bool, string, an enum type, or a reference type.


Workaround: Use a nullable as parameter. IMO this is cleaner anyways since the special value is clearly different and not just a normal value.

void A(DateTime? p=null)
{
}

Another alternative is:

void A(DateTime p=default(DateTime))
{
}

Which shows that a default parameter can use default(T) as valid default parameter value for user defined types.

Or just overload the method for the different number of parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜