Reputation: 36048
how can I test if a dynamic variable is a double for example?
I need to do something like:
void someMethod(dynamic var1)
{
if(var1.isDouble)
{...
}else if(var1 is int)
// do something else....
}
Upvotes: 3
Views: 3691
Reputation: 164281
You can check whether the type is implicitly convertible to double, with the is
keyword:
if (var1 is double)
Upvotes: 0
Reputation: 268215
This scenario has nothing to do with dynamic
keyword as explained by dlev.
Did you mean:
void someMethod(object o)
{
if (o is double) {
double d = (double)o;
// do something with d
} else if (o is int) {
int i = (int)o;
// do something with i
}
}
Either way, this is generally a bad practice unless absolutely needed.
What are you trying to accomplish?
Upvotes: 4
Reputation: 48596
That approach is fine (i.e. var1 is double
), though that's usually not what dynamic
is meant to accomplish. More often, you should dynamic
when you do know what the type will be, but it's difficult or impossible to show that at compile-time (e.g. a COM interop scenario, a ViewBag
in MVC, etc.) You could just use object
if you want to pass a variable of unknown type. Otherwise, the run-time will do the type analysis for you during execution, which can be a big performance hit if that's not what you need.
In general, there could be scenarios where you'd want to use dynamic
as a catch-all container, but this doesn't appear to be one of them. In this case, why not have a number of method overloads that each take the desired type:
void someMethod(double d) { ... }
void someMethod(int i) { ... }
Upvotes: 9