Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value for DateTime in optional parameter [duplicate]

How can I set default value for DateTime in optional parameter?

public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???) {     //Init codes here } 
like image 882
Sadegh Avatar asked Jun 13 '10 04:06

Sadegh


People also ask

What is the default value of DateTime variable?

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.

Is it mandatory to specify a default value to optional parameter?

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.

How do you pass optional parameters?

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.

What is the value of DateTime MinValue in C#?

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.


1 Answers

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 } 
like image 162
LukeH Avatar answered Sep 20 '22 04:09

LukeH