Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand how this phrase is calculated in c#

Tags:

c#

I test this code

int value = (char)+(int)-(float)+(double)-1;

and I get this result (1) that means value is 1! How is this calculated?

EDIT:

I had an interview yesterday in a company and this was their question, and I did not know how this number was obtained 1. So I am trying to understand how this result comes about.

like image 918
Amin Saadati Avatar asked Dec 10 '22 10:12

Amin Saadati


1 Answers

This is really just a lot of casting. The + and - signs are only being used to negate the number. So take the first bit of the expression, that casts -1 to a double:

(double)-1

Then take the result of that and cast it to float:

(float)+(-1)

And so on until you end with a char that is implicitly cast to an int.

like image 90
DavidG Avatar answered Dec 29 '22 05:12

DavidG