Beware of casting an object to a string (e.g. (string)val;) if the underlying value is a numeric type.

I know. I know. I should know better. I should use the convert method instead.

object val=1; //<-- assign an integer value...
string s=(string)val; // <-- can you say invalid cast exception.... 

This is really a simple mistake and one I should not have made but it is so easy to do. Instead you should;

object val=1; //<-- assign an integer value...
string s=Convert.ToString(val); //<-- much better...

-Mathew Nolton

7 Comments

Comments have been disabled for this content.