Null and DateTime

T

tshad

How do you set DateTime to value of nothing?

I tried:

private DateTime dateCreated = "";

which gets me:

User.cs(24,34): error CS0029: Cannot implicitly convert type 'string' to
'System.DateTime'

I tried:

private DateTime dateCreated = null;

which got me:

User.cs(24,34): error CS0037: Cannot convert null to 'System.DateTime'
because it is a value type

I am doing this in my class where I initially define my local variables.

Thanks,

Tom
 
R

Richard Blewett [DevelopMentor]

tshad said:
How do you set DateTime to value of nothing?

I tried:

private DateTime dateCreated = "";

which gets me:

User.cs(24,34): error CS0029: Cannot implicitly convert type 'string' to
'System.DateTime'

I tried:

private DateTime dateCreated = null;

which got me:

User.cs(24,34): error CS0037: Cannot convert null to 'System.DateTime'
because it is a value type

I am doing this in my class where I initially define my local variables.

Thanks,

Tom

Unfortunately, DateTime is a value type and therefore cannot be set to null
(nothing).

In 1.1 you just have to pick a "Magic Value" which indicates to you it
hasn't been set.

In 2.0, C# supports nullable types so you have

DateTime? dt = null; // note the ?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
 
T

tshad

"Richard Blewett [DevelopMentor]" <richard at nospam dotnetconsult dot co
dot uk> wrote in message news:[email protected]...
Unfortunately, DateTime is a value type and therefore cannot be set to
null (nothing).

In 1.1 you just have to pick a "Magic Value" which indicates to you it
hasn't been set.

In 2.0, C# supports nullable types so you have

DateTime? dt = null; // note the ?

Can you do this with ints also?

int? iTest = null;

Thanks,

Tom
 
W

William Stacey [MVP]

Cool. I totally missed any mention of "?" in the 2.0 stuff so far. Good to
know.
 
S

Scott

Instead of the nullable value types (and until 2.0 comes out), as a
convension I always use DateTime.MinValue


Just something else to consider,
Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top