derekantrican
derekantrican

Reputation: 2275

Convert string to type of another variable

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);

Upvotes: 3

Views: 4284

Answers (2)

iDillon
iDillon

Reputation: 122

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.

Upvotes: 1

Eser
Eser

Reputation: 12546

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

Upvotes: 4

Related Questions