10

I want to create an instance of value types like System.String, System.Boolean, System.Int32, etc. I get qualified names of types like System.String or MyNamespace.Employee and I have to create an instance and return back. I use Activator.CreateInstance and FormatterServices.GetUninitializedObject to create instances. But it fails in case of value types. I cannot hard code the logic in case of value types. I need a generic way of creating instances of both value types and reference types.

1
  • 3
    System.String is reference type, not a value type. Commented Jan 4, 2010 at 6:30

4 Answers 4

12

What exactly is it you are trying to do? FormatterServices.GetUninitializedObject is used mainly by serialization code; outside of that you shouldn't really use it. It sounds like you might just need something like TypeConverter, i.e. (for these types)

TypeConverter tc = TypeDescriptor.GetConverter(someType);
object obj = tc.ConvertFromString(s);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, lovely for generic stuff :)
3

What exactly is failing? I tried the following code to see if there is a problem with value types:

var instance = Activator.CreateInstance(typeof(Int32));

It gives me an Int32 instance set to 0.

Where exactly is your code failing? Otherwise I would say the problem lies with the way you are loading the type, not the way you are creating the instance.

2 Comments

Eish Jaco! I just went back to change my 'var' to an 'int', in case 'var' was unfamiliar to the OP, and you sneak in the exact same line of code as me. :-)
Haha - you gotta be quick on the draw :-)
1

For BCL Value Types (and when using Strings to describe types) ensure you are not using C# keywords and ensure the Type is fully qualified with namespace. For example, C# int is successfully created this way with Activator.CreateInstance(..)

    object num = Activator.CreateInstance(Type.GetType("System.Int32"));

You will get failed attempts if you try to use language-specific aliases like "int" or short forms like "Int32".

Comments

0

This works for me:

int x = (int)Activator.CreateInstance(typeof (Int32), true);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.