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.
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
Optional parameters are not mandatory. For instance, there is a method called AddNumber(int firstNumber, int secondNumber) which takes two parameters and returns the sum of two parameters. By default, it is mandatory to pass both parameter values when we call the method.
What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
One workaround is to assign them like this:
public DateTime GetDate(DateTime? start = null, DateTime? end = null){
start = start ?? DateTime.MinValue;
end = end ?? DateTime.MinValue;
Console.WriteLine ("start: " + start);
Console.WriteLine ("end: " + end);
return DateTime.UtcNow;
}
Which can be used like this:
void Main()
{
new Test().GetDate();
new Test().GetDate(start: DateTime.UtcNow);
new Test().GetDate(end: DateTime.UtcNow);
new Test().GetDate(DateTime.UtcNow, DateTime.UtcNow);
}
And works just as expected:
start: 1/01/0001 0:00:00
end: 1/01/0001 0:00:00
start: 8/08/2014 17:30:29
end: 1/01/0001 0:00:00
start: 1/01/0001 0:00:00
end: 8/08/2014 17:30:29
start: 8/08/2014 17:30:29
end: 8/08/2014 17:30:29
Note the named parameter to distinguish between the start
and end
value.
Btw, you don't have to use nullable datetime like all other answers says. You can do it with DateTime
as well:
public DateTime GetDate(
DateTime start = default(DateTime),
DateTime end = default(DateTime))
{
start = start == default(DateTime) ? DateTime.MinValue : start;
end = end == default(DateTime) ? DateTime.MinValue : end;
}
This is unlikely but it won't work as expected if you actually pass the default datetime value to your function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With