Search code examples
c#typesactivatorcreateinstance

How can you instantiate an instance of a type, already set to a specific value, if you only have the string representation of the type and the value?


I have the following four strings; two pairs, each with a string representing of the value and it's data type.

string stringValueOfA = "Hello World!";
string stringTypeOfA  = "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

string stringValueOfB = "44";
string stringTypeOfB  = "System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

I know I can get the Types of each like so...

var typeOfA = Type.GetType(stringTypeOfA);
var typeOfB = Type.GetType(stringTypeOfB);

...and I can activate new instances of said types like this...

var a = Activator.CreateInstance(typeOfA);
var b = Activator.CreateInstance(typeOfB);

...but I'm not sure how to create instances that are set to the value encoded in its string representations stringValueOfA and stringValueOfB.

Whatever the solution, I'd also like to avoid boxing if possible. I don't think it is but I'm hoping I'm wrong.


Solution

  • Many BCL types, including String and Int32, have associated type converters which can be used to convert strings to instances of those types and vice versa. If you're working with one of these types, then you can parse a string like this:

    public static object ConvertFromString(string typeName, string value)
    {
        Type type = Type.GetType(typeName, true);
        TypeConverter converter = TypeDescriptor.GetConverter(type);
        return converter.ConvertFromString(value);
    }
    

    Sample usage:

    object valueOfA = ConvertFromString(stringTypeOfA, stringValueOfA); // returns "Hello World!"
    object valueOfB = ConvertFromString(stringTypeOfB, stringValueOfB); // returns 44 as an int
    

    Note: Because the actual type isn't known at compile time, boxing of value types is unavoidable.