|
-
March 22nd, 2006, 08:32 AM
#1
Urgent : gettype of an object
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
-
March 22nd, 2006, 09:12 AM
#2
Re: Urgent : gettype of an object
Code:
if(objectName.GetType() == typeof(Double)){
...
}
Regards
Hansjörg
-
March 22nd, 2006, 09:14 AM
#3
Re: Urgent : gettype of an object
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
}
}
}
-
March 22nd, 2006, 10:09 AM
#4
Re: Urgent : gettype of an object
Hi,
It would be any risk implemented like this: (or any difference)
if(objectName.GetType() == "System.Double")
?
Thanks
-
March 22nd, 2006, 10:11 AM
#5
Re: Urgent : gettype of an object
Hi,
The code you have written won't compile. Here is how it should be :
Code:
if(objectName.GetType().ToString() == "System.Double")
-
March 22nd, 2006, 10:19 AM
#6
Re: Urgent : gettype of an object
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
-
March 22nd, 2006, 10:36 AM
#7
Re: Urgent : gettype of an object
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.
-
March 22nd, 2006, 10:38 AM
#8
Re: Urgent : gettype of an object
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;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|