joe_pool_is Posted October 3, 2008 Posted October 3, 2008 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? Quote Avoid Sears Home Improvement
joe_pool_is Posted October 3, 2008 Author Posted October 3, 2008 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 } Quote Avoid Sears Home Improvement
MrPaul Posted October 4, 2008 Posted October 4, 2008 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: Quote Never trouble another for what you can do for yourself.
joe_pool_is Posted October 5, 2008 Author Posted October 5, 2008 Re: Nullable types Thanks, MrPaul. I'd seen variables declared using a Question Mark (?) before, but I had no idea what they were called, so there was no way to look them up. Now, I know how to set a DateTime to a null value, and I know what the Question Mark means! I got a 2-for-1! Quote Avoid Sears Home Improvement
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.