Paul Kent

.NET Developer (AngularJS, jQuery, C#, Dependency Injection, Unit Testing, Onion Architecture, Azure Cloud)

Can a C# object that contains an int be cast to a double?

We all know in C# that if you have an int you can cast it into a double like this:

int int_a = 5;
double dbl_a = (double)int_a;

But what if the int was boxed in a System.Object and you tried to cast it to a double like in the code below. Would it run?

object obj_intCastedToObject = (object)int_a;
double dbl_objectCastedToDouble = (double)obj_intCastedToObject; // Is this valid?

The answer is it compiles, but at runtime you get a System.InvalidCastException. Check out the following code snippet on how you could cast this correctly.

Comments are closed