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.