Nano HE
Nano HE

Reputation: 9307

GetType() and Typeof() in C#

itemVal = "0";

res = int.TryParse(itemVal, out 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 ?

Upvotes: 2

Views: 5532

Answers (5)

Cameron
Cameron

Reputation: 98746

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);

Upvotes: 5

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

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

Upvotes: 2

Renato Gama
Renato Gama

Reputation: 16519

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
}

Upvotes: 1

Renato Gama
Renato Gama

Reputation: 16519

If num is an int it will never return true

Upvotes: 1

Neil N
Neil N

Reputation: 25258

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

Upvotes: 1

Related Questions