How do i use Activator.CreateInstance with strings?

Viewed 38956

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?

5 Answers

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

You are trying to do this :

var sz = new string();

Try to compile it, you will understand your error.

You may try :

var sz = Activator.CreateInstance(typeof(string), new object[] {"value".ToCharArray()});

But it looks useless, you should directly use value...

It looks like you're trying to call a constructor which just takes a string - and there isn't such a constructor. If you've already got a string, why are you trying to create a new one? (When you didn't provide any further arguments, you were trying to call a parameterless constructor - which again, doesn't exist.)

Note that typeof(string) is a simpler way to get a reference to the string type.

Could you give us more information about the bigger picture of what you're trying to do?

String actually has no constructor that takes a string as input. There is a constructor that takes a char array so this should work:

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