Samantha J T Star
Samantha J T Star

Reputation: 32778

How can I cast an object to a string if that object may be null?

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

Answers (1)

Christoph Sonntag
Christoph Sonntag

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

Related Questions