Set default value for DateTime in optional parameter

Sadegh picture Sadegh · Jun 13, 2010 · Viewed 85.6k times · Source

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

public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???)
{
    //Init codes here
}

Answer

LukeH picture LukeH · Jun 13, 2010

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
}