Search code examples
c#.netreflectionactivator

How do i use Activator.CreateInstance with strings?


In my reflection code i hit a problem with my generic section of code. Specifically when i use a string.

var oVal = (object)"Test";
var oType = oVal.GetType();
var sz = Activator.CreateInstance(oType, oVal);

Exception

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll

Additional information: Constructor on type 'System.String' not found.

I tried this for testing purposes and it occurs in this single liner too

var sz = Activator.CreateInstance("".GetType(), "Test");

originally i wrote

var sz = Activator.CreateInstance("".GetType());

but i get this error

Additional information: No parameterless constructor defined for this object.

How do i create a string using reflection?


Solution

  • Keep in mind that the string class is immutable. It cannot be changed after it is created. That explains why it doesn't have a parameterless constructor, it could never generate a useful string object other than an empty string. That's already available in the C# language, it is "".

    Same reasoning applies for a string(String) constructor. There is no point in duplicating a string, the string you'd pass to the constructor is already a perfectly good instance of the string.

    So fix your problem by testing for the string case:

    var oType = oVal.GetType();
    if (oType == typeof(string)) return oVal as string;
    else return Activator.CreateInstance(oType, oVal);