29

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:00.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?

Alex
  • 2,681
  • 3
  • 28
  • 43
  • @Downvoter Why the downvote? I felt the question was clear, had a precise answer and was relevant to the site. – Alex Jul 28 '11 at 12:16

2 Answers2

23

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.

Vasea
  • 5,043
  • 2
  • 26
  • 30
18

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 1
    this answers my implied question of 'how can I do what I'm trying to do?', thanks :) – Alex Jul 28 '11 at 10:06
  • You could try using [`readonly`](http://msdn.microsoft.com/en-us/library/acdd6hb7(v=vs.71).aspx) if you're looking to ensure that the value doesn't change. And I believe this can be used in conjunction with nullable type [`?`](http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx). – eternalmatt Jul 28 '11 at 14:47
  • @eternalmatt I don't follow - how does this help having an optional DateTime parameter? If it's optional it'll need a default value, and since I can't provide a compile-time constant it seems CodeInChaos' solution is best. – Alex Jul 28 '11 at 17:00