Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, how to make an increment of int declared as object?

I have an external system which gives me an object value (I know that this value always a boxed integer type). I would like to increment it in the usual way: int value += otherIntValue, but I get an error from the compiler:

Operator '+=' cannot be applied to operands of type

For example:

//source values i cannot to change it
object targetInt = 100;
int incrementedValue = 20;

//usual way - not works
targetInt += incrementedValue;    

//ugly workaround
targetInt = ((int) targetInt) + incrementedValue;

Is there a way to increment instances of int and object with targetInt += incrementedValue;?

like image 921
testCoder Avatar asked Sep 16 '25 04:09

testCoder


1 Answers

Just don't change your code. It's perfectly fine to cast your object to an integer so it is possible to make the addition with another integer.

like image 176
ken2k Avatar answered Sep 18 '25 18:09

ken2k