How can I set default value for DateTime in optional parameter?
public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???) { //Init codes here }
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.
Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression. Every parameter following an optional parameter in the procedure definition must also be optional.
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.
The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar. MinValue defines the date and time that is assigned to an uninitialized DateTime variable.
There is a workaround for this, taking advantage of nullable types and the fact that null
is a compile-time constant. (It's a bit of a hack though, and I'd suggest avoiding it unless you really can't.)
public void SomeClassInit(Guid docId, DateTime? addedOn = null) { if (!addedOn.HasValue) addedOn = DateTime.Now; //Init codes here }
In general, I'd prefer the standard overloading approach suggested in the other answers:
public SomeClassInit(Guid docId) { SomeClassInit(docId, DateTime.Now); } public SomeClassInit(Guid docId, DateTime addedOn) { //Init codes here }
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