Click to See Complete Forum and Search --> : Urgent : gettype of an object
DanielaTm
March 22nd, 2006, 07:32 AM
Hi,
I have an urgent problem:
I have a method which receives 2 objects as parameters.I need to find if one of them is double, string, I mean the type.
How can I do that
hansipet
March 22nd, 2006, 08:12 AM
if(objectName.GetType() == typeof(Double)){
...
}
Regards
Hansjörg
stepi
March 22nd, 2006, 08:14 AM
Hi,
Here is the code for you as example:
private void foo(object o)
{
if (o.GetType() == typeof(Double))
{
///you have a double
}
else
{
if(o.GetType() == typeof(String))
{
//you have string
}
else
{
//handle the code for bad parameter
}
}
}
DanielaTm
March 22nd, 2006, 09:09 AM
Hi,
It would be any risk implemented like this: (or any difference)
if(objectName.GetType() == "System.Double")
?
Thanks
stepi
March 22nd, 2006, 09:11 AM
Hi,
The code you have written won't compile. Here is how it should be :
if(objectName.GetType().ToString() == "System.Double")
DanielaTm
March 22nd, 2006, 09:19 AM
Yes, it worked.
My problem was that I had to use it in a switch.
And I used it like this:
1.
switch (ob1.GetType().ToString())
{
case "System.Double":
switch (ob2.GetType().ToString())
{
case "System.Double":
if (((double)ob1) < ((double)ob2))
return true;
break;
default:
return false;
}
break;
.......
It worked.
and I had to use it like this, because when I tried with typeof(), meaning
2.
switch (ob1.GetType().)
{
case typeof(Double)
.......
said "Ïntegral type expected", didn't worked
My question:
1. why didn't work the second style??
2. Is it ok to leave the code like in the first example?
Thank you,
Daniela
stepi
March 22nd, 2006, 09:36 AM
Hi again,
A switch statment can only take a sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type. Because a Type object can not be converted into any of this integral types, the compiler gives an error. So yes it is ok leaving your code as it is.
jhammer
March 22nd, 2006, 09:38 AM
As far as I know you can use switch statements with value type only.
Here is your code refactored:
if (ob1.GetType() == typeof(Double) && ob2.GetType() == typeof(Double) ){
return (double)ob1 < (double)ob2;
}
return false;
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.