1

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?

11
  • In addition to the answers, note that there's a difference between (string)obj and obj.ToString()... Commented Nov 24, 2014 at 13:41
  • Simply use string value = obj.ToString(); Commented Nov 24, 2014 at 13:42
  • @SriramSakthivel - In this case, yes. But since there is "null exception" in the title, one might also have to take into account that obj could be null. Commented Nov 24, 2014 at 13:45
  • 1
    Btw. if you don't know the exact type, but are certain, that it can only be one of a handfull of known types, you could check that with is/as. if (obj is double) { \\ do double stuff } Commented Nov 24, 2014 at 13:50
  • 1
    Convert.ToString() does the same thing in the end. But it also checks if the given object implements IConvertible or IFormattable beforehand (and calls the more appropriate ToString methods if they do). So if you want those checks, or at least can live with them, then go for it. Yackov just showed the way with possibly the smallest footprint while still being safe. Commented Nov 25, 2014 at 7:17

2 Answers 2

5

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

string str = (obj == null) ? string.Empty : obj.ToString();
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. BTW, I am now using Convert.ToString() instead of .ToString() since the former can handle null values too :)
2

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();

2 Comments

That is superfluous, simply use obj.ToString
@SriramSakthivel That's right. I just want to point why OP can't cast directly to string as (string)obj in my answer instead of how to get it's string representation. But I added to my answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.