Converting DateTime? to itself throws invalidcastexception

A

Andrus

Convert.ChangeType((DateTime?)DateTime.Now, typeof(DateTime?), null);

throws exception

Invalid cast from 'System.DateTime' to 'System.Nullable`1[[System.DateTime,
mscorlib, Version=2.0.5.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]'.

How to fix this ?

How to create generic type converter with same parameters as
Convert.ChangeType which converts between value types (including nullable
value types) ?

Should we use lot if if statements to use casts to fix this
Convert.ChangeType() issue before calling it or is there better solution ?

Andrus.
 
G

Gregory A. Beamer

Convert.ChangeType((DateTime?)DateTime.Now, typeof(DateTime?), null);

throws exception

Invalid cast from 'System.DateTime' to
'System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.5.0,
Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.

How to fix this ?

Why do you need to convert? The DateTime will implicitly convert to a
nullable DateTime.

This works fine:

DateTime? dt = DateTime.Now;

as does this:

DateTime? dt2 = new Nullable<DateTime>(DateTime.Now);

Am I missing something here?

Peace and Grace,


--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
| Think outside the box! |
*******************************************
 
J

Jeroen Mostert

Andrus said:
Convert.ChangeType((DateTime?)DateTime.Now, typeof(DateTime?), null);

throws exception

Invalid cast from 'System.DateTime' to
'System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.5.0,
Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.

How to fix this ?
This is a well-known shortcoming of Convert.ChangeType(). Nullable types are
treated specially by the CLR, unfortunately in such a way that
Convert.ChangeType() as written is unable to convert to a nullable type
(converting *from* a nullable type works, if you are not also converting to
a nullable type). See http://aspalliance.com/852 for one way to work around it.
 

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