How to cast int to short

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I have a custom function which accept short as parameter.
for example:

public void myFun(short myShor)
{...}

Now I have a integer (int i), I want to take as the aprameter of myFun,
How can I cast i to short ?
 
ad said:
I have a custom function which accept short as parameter.
for example:

public void myFun(short myShor)
{...}

Now I have a integer (int i), I want to take as the aprameter of myFun,
How can I cast i to short ?

myFun ((short)i);
 
Derrick Coetzee said:
Note that, by default, C# checks for integer overflow when performing a cast
in this obvious way. If you prefer to truncate the most significant bits,
you either need to remove them beforehand using a bitmask or perform the
cast inside an "unchecked {}" block. You can read more about unchecked here:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csre
f/html/vclrfunchecked.asp

No, by default C# *doesn't* check for overflow, except for compile-time
constant expressions. So:

// Doesn't compile
uint x = (uint)-1;
// Does compile
uint x = unchecked((uint)-1);

// Compiles and runs without exception
int y = -1;
uint x = (uint)y;

// Compiles but throws an exception
int y = -1;
uint x = checked((uint)y);

Note that the default behaviour can also be controlled by a compiler
switch or project setting.
 
Jon said:
Derrick Coetzee said:
myFun ((short)i);

Note that, by default, C# checks for integer overflow when
performing a cast in this obvious way. [...]

No, by default C# *doesn't* check for overflow, except for
compile-time constant expressions.

Sorry, my mistake - I'm used to this option being on. I do personally
recommend that the /checked option (Build->Advanced->Check for arithmetic
overflow/underflow) is always used, as this can help to find bugs and
prevent potential security issues, as well as provide conceptual safety
guarantees (and I think it should be on by default). If profiling reveals
that they're slowing down a bottleneck, or if you want the C behaviour of
arithmetic mod 2^word size, you can always wrap the relevant code in
unchecked { }. Thanks for the correction, Jon.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top