I have this function that returns a reference type. Now, this function has two optional parameters both of which are instances of the DateTime
class. The function is something like this:
public DateTime GetDate(DateTime start = DateTime.MinValue, DateTime end = DateTime.MinValue)
{
// Method body...
}
The error from VS is:
Default parameter value for 'start' must be a compile-time constant
Of course, the error applies to the second parameter and I perfectly understand what is happening.
What I really want is to know if there is a way to go about this, that is, having optional parameters in the method. Right now, what I have done is to create an overload; I mean, I have created a parameterless function GetDate()
and a two-parameter overload of it.
This is not really a problem but I just want to know if there is a way to do it.
Btw, you don't have to use nullable datetime like all other answers says. You can do it with
DateTime
as well:This is unlikely but it won't work as expected if you actually pass the default datetime value to your function.
The only way would be to do it like this (a bit more code, but it gives you optional args):
One workaround is to assign them like this:
Which can be used like this:
And works just as expected:
Note the named parameter to distinguish between the
start
andend
value.You can set the
DateTime
to be nullable and then convert toDateTime.Min
if no parameter is provided: