user1891983
user1891983

Reputation: 13

Valid ObservableCollection cast throws InvalidCastException

I am receiving an InvalidCastException for setting two types equal to each other. Thoughts on the particular behavior that might cause this?

Screenshots of Editor, Exception, Watch, and References.

SOLUTION:

Daniel Hilgarth is correct, it was the line of code above that was throwing the exception. I was casting a null value as a nullable value (DateTime?), but implicit casts cannot convert null values. In order to cast properly, you must use the AS keyword.

governanceTemplateTimestamp = (DateTime?)dr["GovernanceTemplateTimestamp"]; //Invalid

governanceTemplateTimestamp = dr["GovernanceTemplateTimestamp"] as DateTime?; //Valid

Upvotes: 1

Views: 502

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

The exception is most likely happening at the line above. The line that is marked as the offending one isn't executing any cast.
I guess that GovernanceTemplateTimestamp is DBNull in your DataRow. DBNull can't be cast to DateTime?.

Upvotes: 2

Related Questions