Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

see what type is a dynamic variable c#

Tags:

c#

dynamic

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....


}
like image 797
Tono Nam Avatar asked Jan 25 '26 06:01

Tono Nam


2 Answers

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) { ... }
like image 154
dlev Avatar answered Jan 27 '26 20:01

dlev


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?

like image 35
Dan Abramov Avatar answered Jan 27 '26 19:01

Dan Abramov