If I have a variable "param" that can be either an int, double, or string, how do I assign another string to param in the most efficient way? Currently what I'm doing is something like this:
string s = "5";
switch (param)
{
case param.GetType() == "System.Double":
param = Convert.ToDouble(s);
break;
case param.GetType() == "System.Int32":
param = Convert.ToInt32(s);
break;
case param.GetType() == "System.String":
default:
break;
}
I was hoping to condense it to something like this (pseudo-code):
param = (typeof(param))s;
or
param = s as typeof(param);
you can use
Convert.ChangeType(s,param.GetType())
https://msdn.microsoft.com/en-us/library/dtb69x08(v=vs.110).aspx
or
ConvertTo(s,param.GetType())
https://msdn.microsoft.com/en-us/library/y13battt(v=vs.110).aspx
I'm not sure what your overall goal is with just this piece of code, but you can always just change the type of the variable:
Convert.ChangeType(s, typeof(param));
After which, you can simply assign it.
After thinking about it, you can then just go ahead and use your variable now if it's successful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With