Carlos Hdez Barbera
Carlos Hdez Barbera

Reputation: 23

Convert from String to type stored in Type variable

I'm trying to do a kind of debug console in Unity to be able to change - for example - enable/disable boolean values at run-time.

There's a point where I have a value that I want to set in a certain variable but this value is stored as a string (input from the user) and I need to cast it to the type of that variable (stored in a Type variable) but I don't know if this is possible.

This is the part of my code where I have the problem:

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    placeToSet.SetValue(null, //here I need to convert "toSet"); 
}

I would like to know if this is possible and how can I do it.

Upvotes: 1

Views: 410

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

TypeDescriptor provides a fairly robust way to convert a string to a specific type. Of course, this will only work for a handful of types that have fairly straightforward parsing.

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    var value = TypeDescriptor.GetConverter(type).ConvertFrom(toSet);
    placeToSet.SetValue(null, value); 
}

Upvotes: 1

Related Questions