Identifing non-assigned DateTime Variable

  • Thread starter Thread starter Rafael Veronezi
  • Start date Start date
R

Rafael Veronezi

Hello guys,
I have a simple doubt...
How can I identify or nullaby a DateTime variable?

I store a date input from a user, that will be saved on the database. Since
this is a optional field, I need to determine if the user has passed a value
to the variable, if he has, I will pass that value as parameter to my query,
otherwise, I will pass a DBNull value.

Do you understand the problem?
I think it's easy, I'll be very thank if someone help me...
Thanks,
Rafa
 
Rafael Veronezi said:
Hello guys,
I have a simple doubt...
How can I identify or nullaby a DateTime variable?

You can't. There's no such thing.
I store a date input from a user, that will be saved on the database. Since
this is a optional field, I need to determine if the user has passed a value
to the variable, if he has, I will pass that value as parameter to my query,
otherwise, I will pass a DBNull value.

A DateTime variable always has a value, or it can't be used at all - it's exactly
the same as any other time. (Take an "int" for example.)

When you store the date input, you need to store the DateTime and
whether or not it's "valid" or not. Alternatively, you could pick some
arbitrary DateTime to be an invalid one (e.g. the lowest value DateTime
can take) and use that as effectively like null.
 
I think I found myself the reply from my question, just to see if it's the
best method, look with me...

I have a DateTime field in a class...
I instantiated the class... But didn't assing any value to that dt field...
Anyways, the field is already instantiated...
It's value is something like 1/1/0001 00:00:00
So I test equality with a new DateTime(0) (where 0 is the number of
ticks)...
The return of the equality was true, when I change to 1, it returns false...
Look at the sample:

using System;

public class MainClass
{
public static void Main()
{
Test t = new Test();

Console.WriteLine(t.myDt.Date.ToString());
Console.WriteLine(t.myDt == (new DateTime(0)));
}
}

public class Test
{
public DateTime myDt;
}

The output is:
1/1/0001 00:00:00
True

Is this the best way to determine the initialization of a DateTime
structure?
Thanks
 
Is this the best way to determine the initialization of a DateTime
structure?

That depends on whether the value for new DateTime(0) is potentially a
legal value in your app. If so, you clearly can't use it as a
"special" value. Otherwise, yes, you can use it.
 
May be better to do something like:

Console.WriteLine(t.myDt == DateTime.MinValue);

This way you aren't hard-coding a value, just using what the DateTime class
itself
initialises it's value to.

--pat
 
If it is a nullable field, just check for DBNull.Value when you read and if
not, assign to a DateTime.
 
Back
Top