Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

How do I check for an uninitialized DateTime?

 

If I start my code by simply declaring a DateTime value:

 

DateTime time1;

 

Then the compiler gives me the error that the field was uninitialized.

 

Seting the DateTime value to null is not legal though, it seems:

 

DateTime time1 = null;

 

How am I supposed to be initializing a DateTime value?

Posted

Some of you may be wondering, "Why would you want a null DateTime?"

 

Here's an example of somewhere that I have to initialize the DateTime object with data that is *not* what I want:

/// <summary>
/// Synchronize the Time on the SQL Server with the time on the device
/// </summary>
private void SyncWithSqlTime(DateTime sqlTime) // pass in or query for time to set on device
{
 SYSTEMTIME st = new SYSTEMTIME();
 sqlTime = DateTime.Now; // checking to see if sqlTime has been set doesn't seem possible
 m_lastError = string.Empty;
 try
 {
   m_db.Open(); // Sql Connection object
   using (SqlCommand cmd = new SqlCommand("SELECT GetDate() AS [CurrentDateTime]", m_db))
   {
     SqlDataReader r = cmd.ExecuteReader();
     while (r.Read() == true)
     {
       sqlTime = (DateTime)r["CurrentDateTime"];
     }
   }
 }
 catch (InvalidOperationException e)
 {
   Console.WriteLine(e.StackTrace);
 }
 catch (SqlException e)
 {
   Console.WriteLine(e.StackTrace);
 }
 finally
 {
   m_db.Close();
 }
 st.FromDateTime(sqlTime); // Convert to SYSTEMTIME
 SetLocalTime(ref st); // PInvoke Win32 API to set time
}

Posted

Nullable types

 

If using .NET 2 or later, you can use nullable types:

 

DateTime? sqlTime = null;

 

Alternatively, I tend to initialize variables to something like DateTime.MinValue and then test for that.

 

Good luck :cool:

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...