This is my method signature. While trying to pass end
as an optional parameter it gives me this error. What should I do to resolve this? Why isn't DateTime.MinValue
a constant?
public static void DatesToPeriodConverter(DateTime start, DateTime end = DateTime.MinValue, out string date, out string time)
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
The designers considered the feature and rejected it as not useful enough to be worth the cost of implementing. The designers considered the feature and rejected it as being confusing because it uses similar syntax to default value parameters, but has a quite different meaning.
TimeSpan Range The default value is TimeSpan(0, 0, 0, 0, 0) . MaximumTime(TimeSpan): Defines the upper limit of the available selection range. The default value is TimeSpan(30, 23, 59, 59) .
A variable in C# can be made into a compile-time constant by adding the const keyword before the data type. This modifier means that the variable cannot be changed and it must therefore be assigned a value at the same time as it is declared.
DateTime.MinValue
is not a const
, because the language doesn't like const
on DateTime
. One option is to use DateTime?
instead, i.e.
public static void DatesToPeriodConverter(DateTime start, DateTime? end = null, out string date, out string time) { var effectiveEnd = end ?? DateTime.MinValue; // ... }
However, you will still have the issue of having non-default parameters after default parameters - you may need to re-order them to use that as a default.
Use regular method overloads instead:
public static void DatesToPeriodConverter(DateTime start, out string date, out string time) { DatesToPeriodConverter(start, DateTime.MinValue, out date, out time); } public static void DatesToPeriodConverter(DateTime start, DateTime end, out string date, out string time) { }
Atlernatively, default(DateTime)
is the same as DateTime.MinValue
and is compile time constant, but I tend to err away from using this style (there's no guarantee in future that default(DateTime)
will equal DateTime.MinValue
):
public static void DatesToPeriodConverter(DateTime start, DateTime end = default(DateTime), out string date, out string time)
Or as Marc suggests, use DateTime?
which allows a null
default value.
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