Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Is Operator with Value Types C#

What am I missing? I do not see an answer on stackoverflow, but could have missed it. It seems like the "is" operator should work (i.e. evaluate to true) for the case where

short j = 1;
int k = 2; 

if (j is int)
   Console.WriteLine("all values of j will fit into k");
else
   Console.WriteLine("all values of j will not fit into k");

I tried making the int and short nullable which did not work as well. The rationale for the conditional being true is that all values of short will fit into a variable of type int (which is potentially wrong based on the result - i.e. the "If (j is in)" evaluates to false. Thanks

like image 748
Buck Avatar asked Apr 15 '26 20:04

Buck


1 Answers

The rationale for the conditional being true is that all values of short will fit into a variable of type int.

You're holding a paperback copy of the book The Hobbit, and someone asks you "is that thing you're holding a movie?" Do you say yes, because there's was a movie made of the book? Or do you say "no, I'm holding a paperback book, and a book is not a movie." ?

Just because there is an int that corresponds to every short does not make a short an int. The is operator tells you whether the thing you have in hand is of a particular type, hence the name "the is operator". It doesn't tell you whether there is a different thing of a different type that happens to correspond to the thing you have in hand.

like image 103
Eric Lippert Avatar answered Apr 18 '26 09:04

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!