typeof()

  • Thread starter Thread starter rua17
  • Start date Start date
R

rua17

Hello:

I want to know if somo variable is integer, real or string but typeof
returns Int16, Int32, etc, because of that my if() statement has to compare
if X is Int32 or Int64 or ...

Any idea how to reduce the if statement?

thanks
 
rua17 said:
I want to know if somo variable is integer, real or string but typeof
returns Int16, Int32, etc, because of that my if() statement has to compare
if X is Int32 or Int64 or ...

Any idea how to reduce the if statement?

Well, you could have two collections (eg Hashtables), one containing
the types of Int32, Int64, UInt32 etc, another containing the types of
Single and Double, and then just a test for string...
 
Use the "is" keyword.

You can do something like:

if (23 is int)
{
// Do your stuff
}

-vJ
 
Thanks


Jon Skeet said:
Well, you could have two collections (eg Hashtables), one containing
the types of Int32, Int64, UInt32 etc, another containing the types of
Single and Double, and then just a test for string...
 
The easiest way to do this is

if (obj is string)
{

}
else if (obj is float || obj is double)
{

}
else if (obj is int || obj is uint || obj is short || obj is ushort ||
obj is long || obj is ulong || obj is byte || obj is sbyte)
{

}
else
{
// Unexpected Type
}

The previous code is preferable, but you can still use if statement with
typeof, by comparing Type objects:

if (obj == null)
{
// Unexpected value

}
if (obj.GetType() ==
typeof(string))
{

}
else if (obj.GetType() == typeof(float) || obj.GetType() ==
typeof(double))
{

}
else if (/*check for integral types in the same way*/)
{

}
else
{
// Unexpected Type
}

Please let me know if you need more clarification

Karim Elias
C# Compiler QA
Microsoft
 
Back
Top