I am receiving an InvalidCastException for setting two types equal to each other. Thoughts on the particular behavior that might cause this?
- Defining this.governanceTemplateList with the field definition does not change the exception.
- Defining this.governanceTemplateList as a new ObservableCollection in the constructor throws the exact same exception.
- The following code is in a WCF service library, using .NET 4.0.
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
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
GovernanceTemplateTimestampisDBNullin your DataRow.DBNullcan’t be cast toDateTime?.