c# - Is there a difference between cast and strong type assignment? -


i sort of ran today when writing code. take following example:

long valuecast  = (long)(10 + intvariable); long valuetyped = 10l + intvariable; 

is there difference between these 2 or compiled same thing? there convention 1 on other?

so know isn't critical question (both work). i'm curious difference(s) might be!

edit - modified code example closer original scenario is. wanted question clear replaced variable constant. didn't realize compiler arithmetic automatically (thereby changing answers question)

yes, there's big difference between two. not particular values, exact same expression different values show difference.

in first version, addition done in 32-bit arithmetic, , result converted long.

in second version, first operand long, second operand promoted long , addition performed in 64-bit arithmetic.

of course in case compiler perform arithmetic anyway (and come same conclusion in both cases), it's important understand difference between converting result of operation, , converting 1 of operands of operation.

as example:

unchecked {     long valuecast  = (long)(2000000000 + 2000000000);     long valuetyped = 2000000000l + 2000000000;     console.writeline(valuecast);     console.writeline(valuetyped); } 

result:

-294967296 4000000000 

note has done in explicitly unchecked context, otherwise first addition wouldn't compile - you'd error of "cs0220: operation overflows @ compile time in checked mode".


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -