How to handle null exception when converting from object to string?

Just curious:

These lines throw Invalid Cast Exception: Unable to cast object of type 'System.Double' to type 'System.String'.

 Object obj = new object();
 obj = 20.09089;
 string value = (string)obj;

I receive the obj value from a library.

How to simply convert to string when we don't know the type of object while enumerating?

Upvotes: 1

Views: 1623

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

This is an boxing / unboxing issue.

20.09089 is a double by default. When you wanna unbox a primitive type from object, you need to unbox it the original type first.

Object obj = new object();
obj = 20.09089;
string value = ((double)obj).ToString();

or simplify;

Object obj = new object();
obj = 20.09089;
string value = obj.ToString();

Upvotes: 2

ymz
ymz

Reputation: 6914

that is why every object in .net has the ToString() method (inherited from Object)

string str = (obj == null) ? string.Empty : obj.ToString();

Upvotes: 5

Related Questions