Reputation: 32778
I have this code:
var answer = (string)parameters[0].Value;
It's failing with a message:
Message = "Unable to cast object of type 'System.DBNull' to type 'System.String'."
Is there some way I can do the cast even if the Value is null and stop the exception?
Upvotes: 1
Views: 76
Reputation: 4629
var answer = ""
if(parameters[0].Value != DBNull.Value) {
answer = (string)parameters[0].Value
}
Or shorter :
var answer = parameters[0].Value != DBNull.Value ? (string)parameters[0].Value : ""
And your empty result is not null, it is DBNull.Value as your parameters seem to come from something DB-related ;)
P.S.: I don't have a visual studio by hand to test it but it should work ;)
Upvotes: 2