Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a null from Function which returns a DateTime

Tags:

c#

asp.net

 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) -> ""

like image 446
Sudantha Avatar asked Dec 22 '11 09:12

Sudantha


People also ask

Can you set DateTime to null?

Using the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.

What is return null in C#?

A null object is an object without behavior like a stub that a developer can return to the caller instead of returning null value. The caller doesn't need to check the order for null value because a real but empty Order object is returned.


2 Answers

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;  
    }  
}
like image 67
Pleun Avatar answered Oct 15 '22 03:10

Pleun


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.

like image 33
ChrisBint Avatar answered Oct 15 '22 04:10

ChrisBint