Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to type of another variable

Tags:

c#

casting

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);
like image 752
derekantrican Avatar asked May 21 '26 21:05

derekantrican


2 Answers

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

like image 59
Eser Avatar answered May 23 '26 12:05

Eser


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.

like image 38
iDillon Avatar answered May 23 '26 12:05

iDillon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!