How to automatically cast variables in C#?

.net, c#, vb.net

Solution

In this particular case, I think you want `Convert.ChangeType`:

object data = Convert.ChangeType(toBeCasted, whatIsMyType);

Of course that only works with a limited set of types - but then so does casting in the first place. If you can tell us more about what you're trying to do, it would be helpful. There may very well be a better approach.

Problem

Here is a example. ``` var tobeCasted = 1; object data = null; if (whatIsMyType == typeof(int)) { data = (int)tobeCasted; } else if (whatIsMyType == typeof(float)) { data = (float)tobeCasted; } ``` However the above code is manually detected each data type. I'm looking for a one line general solution like following : ``` data = (whatIsMyType)tobeCasted; ```

Original source