32

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?

1
  • @Downvoter Why the downvote? I felt the question was clear, had a precise answer and was relevant to the site. Commented Jul 28, 2011 at 12:16

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@jazmatician DateTime is a value type. See msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
I knew that was wrong when I typed it, but couldn't put my finger on it. :)
21

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.

3 Comments

this answers my implied question of 'how can I do what I'm trying to do?', thanks :)
You could try using readonly if you're looking to ensure that the value doesn't change. And I believe this can be used in conjunction with nullable type ?.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.