开发者

GetType() and Typeof() in C#

开发者 https://www.devze.com 2023-02-19 07:54 出处:网络
itemVal = \"0\"; res = int.TryParse(itemVal, out开发者_StackOverflow num); if ((res == true) && (num.GetType() == typeof(byte)))
itemVal = "0";

res = int.TryParse(itemVal, out开发者_StackOverflow num);

if ((res == true) && (num.GetType() == typeof(byte)))  
    return true;
else
   return false;  // goes here when I debugging.

Why num.GetType() == typeof(byte) does not return true ?


Because num is an int, not a byte.

GetType() gets the System.Type of the object at runtime. In this case, it's the same as typeof(int), since num is an int.

typeof() gets the System.Type object of a type at compile-time.

Your comment indicates you're trying to determine if the number fits into a byte or not; the contents of the variable do not affect its type (actually, it's the type of the variable that restricts what its contents can be).

You can check if the number would fit into a byte this way:

if ((num >= 0) && (num < 256)) {
    // ...
}

Or this way, using a cast:

if (unchecked((byte)num) == num) {
    // ...
}

It seems your entire code sample could be replaced by the following, however:

byte num;
return byte.TryParse(itemVal, num);


Simply because you are comparing a byte with an int

If you want to know number of bytes try this simple snippet:

int i = 123456;
Int64 j = 123456;
byte[] bytesi = BitConverter.GetBytes(i);
byte[] bytesj = BitConverter.GetBytes(j);
Console.WriteLine(bytesi.Length);
Console.WriteLine(bytesj.Length);

Output:

4
8


because and int and a byte are different data types.

an int (as it is commonly known) is 4 bytes (32 bits) an Int64, or Int16 are 64 or 16 bits respectively

a byte is only 8 bits


If num is an int it will never return true


If you wanna check if this int value would fit a byte, you might test the following;

int num = 0;
byte b = 0;

if (int.TryParse(itemVal, out num) && byte.TryParse(itemVal, b))
{
    return true; //Could be converted to Int32 and also to Byte
}
0

精彩评论

暂无评论...
验证码 换一张
取 消