Normally, if I have a nullable type for an optional parameter, I would put null as the default value. This way I know that if the value is null, the caller doesn't want to specify any value for that one.
public void Foo(string text, string text2= null);
If the parameter is normally a positive integer, I can use a negative number
public void Foo(string text, int index=-1);
How about DateTime? It is not nullable, and (as far as I know) it doesn't have a meaningless number that cannot be a true input either (like -1 for positive integer). Or is there? What would you use in this situation?
I also know that I can use the nullable DateTime
type, but this means that the method caller will have to use Nullable as well as opposed to just conveniently pass a DateTime.
You can make value types nullable using the ?
operator in C#:
DateTime? myDate = null;
From this, you can make the parameter optional:
void Foo(DateTime? myDate = null)
{
}
Further reading on Nullable Types.
This is not the only way to skin the cat however, you can use default(DateTime)
, however you cannot use DateTime.MinValue
, MaxValue
, or Now
in optional parameters because they are not compile time constants.
Of course, you don't need to use optional parameters, you can use overloaded methods if you wish to make use of Min, Max, or Now.
void Foo()
{
Foo(DateTime.MinValue);
}
void Foo(DateTime d)
{
}
If you want to go overkill (well, maybe not overkill, plenty of valid reasons to do this), then you could define a new date type that understands when it has a value:
class SmarterDateTime
{
public bool IsSet { get; set; }
// Wrapper around DateTime etc excluded.
}
As for what should be the default, you can choose to make any date represent a default if you wish, but for things like optional parameters you'll have limitations.
Personally, I tend to use DateTime.MinValue
.