Home > Software engineering >  value is ushort returning false for values like 0, 100 etc even if it is ushort
value is ushort returning false for values like 0, 100 etc even if it is ushort

Time:01-05

I have a requirement where I need to determine specifically that an object value is ushort, short, int, long or double, like the below code.

string dataType = "";
object value = 0;
 if (value is ushort)
                {
                    dataType = "ushort";
                }
                else if (value is short)
                {
                    dataType = "short";
                }
                else if (value is int || value is long
                   || value is ulong  || value is double)
                {
                    dataType = "int";
                }
                else
                {
                    dataType = "float";
                }  

But the line

if (value is ushort) 

is false for 0 or any other value less than 65535. Why is it so. It qualifies to an ushort right? Thanks

I have checked with value is ushort for values like 0, 100,200 etc. All are false.

CodePudding user response:

A box has a type. A boxed object is only is ushort if the box was created from a ushort (or a ushort? due to the special boxing rules for Nullable<T>).

An int with value 0, when boxed, is still a boxed int. It doesn't become a ushort just from the scale of the value. is is not the same as "could be fitted into a"

CodePudding user response:

You would have to cast the number literal to ushort before boxing it, otherwise it's type if going to be int by default:

object value = (ushort)0;
  • Related