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
Printable View
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
RegardsCode:if(objectName.GetType() == typeof(Double)){
...
}
Hansjörg
Hi,
Here is the code for you as example:
Code: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
}
}
}
Hi,
It would be any risk implemented like this: (or any difference)
if(objectName.GetType() == "System.Double")
?
Thanks
Hi,
The code you have written won't compile. Here is how it should be :
Code:if(objectName.GetType().ToString() == "System.Double")
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
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.
As far as I know you can use switch statements with value type only.
Here is your code refactored:
Code:if (ob1.GetType() == typeof(Double) && ob2.GetType() == typeof(Double) ){
return (double)ob1 < (double)ob2;
}
return false;