1

I am new to C# and just start to learning it. I have tried to create a Mathematics class for which I have added a method Add. This method will add a number with the current value.

The implementation is like below:

public class Mathmatics
{
    private int value = 0;
    public int Add(object a)
    {
        int b;
        int b = (int)a; //Thorws this error "InvalidCastException: Specified cast is not valid." for value 10.5 or any other decimal value.
        this.value += b;
        return this.value;
    }
}

The above method works fine if I give the input value any integer type. But for decimal type value it fails.

My question is why the object type cannot be cast to int if decimal value is given as input, as if it can cast when Integer value is given?

I have found that I can use Convert.ToInt32() to convert the value to integer but I am not for that solution. I am just curious to know the reason.

If anybody can help me to understand the reason. Thanks in advance.

coderhunk
  • 153
  • 1
  • 6

1 Answers1

1

Welcome to the C# world of Boxing and Unboxing. In this case your code tried to Unbox the object type value to int type.

The first thing is Unboxing casting the reference type instance to value type. Unboxing requires an explicit cast. The runtime checks that the stated value type matches the actual object type, and throws an InvalidCastException if the check fails.

For this reason your application is failed to Unbox as the value type is decimal but you want to cast int type. You have to first cast to the similar type then perform the numeric conversion. You can do like this:

int b = (int)(double)a;

Here (double) perform an unboxing and (int) perform numeric conversion.

But be careful, if you use this code without checking type, you will face issue for int type value as input (same reason as previous). So, you have to check the type first and then unbox. So, its better to use Convert.ToInt32() in this case otherwise you have to check the type first.

Mainul
  • 879
  • 7
  • 10