tags:

views:

43

answers:

3

I have some code that looks like

else if (oField.FieldType.IsClass)
{
    //var t = oField.FieldType.new()
    someObj.fill_data(t);
    oField.SetValue(o, t);
}

I dont know how to allocate var t. How might i do this? There no way for me to know what the type could be so writing FieldType.IsAssignableFrom(KnownType) can not be a workaround.

+4  A: 

Try Activator.CreateInstance:

object t = Activator.CreateInstance(oField.FieldType);

This assumes that type FieldType has a default constructor.

Jason
That is exactly how I would do it....
CSharpAtl
Worked like a charm :)
acidzombie24
I marked the other guy as accepted for other ppl to see his example code. I like your answer better tho. (and he is < 10k)
acidzombie24
+1  A: 

Perhaps you should look into the Type.GetConstructor(...).Invoke(...) of the returned Type.

Zach Johnson
At a minimum, you have to either guess that there is a constructor with no parameters (so pass in `new Type[] {}` to `GetConstructor`) or know a specific parameter type list for the constructor. The latter seems unlikely.
Jason
Interesting, +1
acidzombie24
+1  A: 

Here is some example code:

 class TypeTest
 {
     int m_parameter;
     public TypeTest()
     {
     }
     public TypeTest(int parameter)
     {
         m_parameter = parameter;
     }
     public int Param { get { return m_parameter; } }
}

//method1 - Using generic CreateInstance
TypeTest defConstructor = Activator.CreateInstance <TypeTest>();

//method2 - Using GetConstructor
ConstructorInfo c = typeof(TypeTest).GetConstructor(new Type[] { typeof(int)});
TypeTest getConstructor = (TypeTest)c.Invoke(new object[] { 6 });

//method3 - Using non-generic CreateInstance
TypeTest nonDefaultConstructor = (TypeTest)Activator.CreateInstance(typeof(TypeTest), 6);
Igor Zevaka