Jerri Kangasniemi Jerri Kangasniemi - 2 months ago 12
C# Question

Why does the declaration of a DateTime const give a compiler error but not optional parameter?

I'm no good with titles, methinks. But bear with me: I know why reference types in themselves cannot be declared const - they must be fully evaluable at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.

So it makes sense that

const DateTime x = some date
is not valid. But following that logic, I should not be able to pass for example
DateTime d1 = default(DateTime)
as an optional parameter, just like I cannot declare a
const DateTime d1 = default(DateTime)
, since optional parameters have to be compile-time constants? This has always been something I've had that attitude of "meh. just the way it is" about, but I got curious now.

Isn't a compile-time constant a compile-time constant? As in, a constant is a constant?

Of course, it might just as well be that my IDE (Visual Studio) just gives an error because DateTime is not allowed as
and it would've compiled fine as a


Have a look at the msdn article on optional parameters. When the data type is a value type (enum, struct) you may initiate an optional parameter with an empty constructor:

static void Foo(string s, DateTime opt = new DateTime())

Or with the default keyword. This isn't true for reference types.