Sudantha
Sudantha

Reputation: 16184

Return a null from Function which returns a DateTime

 public static DateTime ResolveDate()
 {
   return null;
 }

Im required to return a null value from a function which returns a DateTime Type .. My Main Objective is to NOT to use MinValue or return a new Datetime(); [Which Returns a Default Date] and Frontend display the Date as a Empty Value (Blank) -> ""

Upvotes: 8

Views: 32514

Answers (4)

nshouppuohsn
nshouppuohsn

Reputation: 119

    bool somecondition = true;
    public DateTime? ResolveDate()
    {

        DateTime? date = null;
        if (somecondition == true)
        {
            date = DateTime.Now;
            return DateTime.Now;
        }
        else return date;
    }

Upvotes: 1

Pleun
Pleun

Reputation: 8920

public static DateTime? ResolveDate() 
{ 
    if ( someconditon = true )
    {
        return DateTime.Now
    }
    else
    {
        return null; 
    } 
}

An alternative is to use something like TryParse is working

Public static bool TryResolve (out Resolvedate)
{
    if ( someconditon = true ) 
    { 
        Resolvedate = DateTime.Now 
        return true;
    } 
    else 
    {
        return false;  
    }  
}

Upvotes: 28

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

You can either return a Nullable<DateTime> like so:

public static DateTime? ResolveDate()
{
  if (notResolvable) 
  {
    return null;
  }
}

Which would be useable like so:

var date = ResolveDate();
if (date.HasValue) 
{
  // Use date.Value here
}

Or use the Try naming convention like so:

public static bool TryResolveDate(out DateTime date) 
{
  date = default(DateTime);
  if (notResolvable) 
  {
    return false;
  }
}

Which would be useable like so:

DateTime date;
if (TryResolveDate(out date)) 
{
  // Use date here
}

Upvotes: 2

Kinexus
Kinexus

Reputation: 12904

Make it nullable

   public static DateTime? ResolveDate()
        {
            return null;
        }

You can then return null as you want and check accordingly

Have a read of this Nullable Types for more information.

Upvotes: 5

Related Questions