tags:

views:

1131

answers:

3

Lets say i have this class:

class Test123<T> where T : struct
{
    public Nullable<T> Test {get;set;}
}

and this class

class Test321
{
   public Test123<int> Test {get;set;}
}

So to the problem lets say i want to create a Test321 via reflection and set "Test" with a value how do i get the generic type?

A: 

This should do it more or less. I have no access to Visual Studio right now, but it might give you some clue how to instantiate the generic type and set the property.

// Define the generic type.
var generic = typeof(Test123<>);

// Specify the type used by the generic type.
var specific = generic.MakeGenericType(new Type[] { typeof(int)});

// Create the final type (Test123<int>)
var instance = Activator.CreateInstance(specific, true);

And to set the value:

// Get the property info of the property to set.
PropertyInfo property = instance.GetType().GetProperty("Test");

// Set the value on the instance.
property.SetValue(instance, 1 /* The value to set */, null)
Patrik
Sure that would work but lets say i dont know that the generic parameter is Int.. all i know is the type of Test321.
Petoj
+2  A: 

Since you are starting from Test321, the easiest way to get the type is from the property:

Type type = typeof(Test321);
object obj1 = Activator.CreateInstance(type);
PropertyInfo prop1 = type.GetProperty("Test");
object obj2 = Activator.CreateInstance(prop1.PropertyType);
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test");
prop2.SetValue(obj2, 123, null);
prop1.SetValue(obj1, obj2, null);

Or do you mean you want to find the T?

Type t = prop1.PropertyType.GetGenericArguments()[0];
Marc Gravell
A: 

Try something like this:

using System;
using System.Reflection;

namespace test {

    class Test123<T> 
        where T : struct {
        public Nullable<T> Test { get; set; }
    }

    class Test321 {
        public Test123<int> Test { get; set; }
    }

    class Program {

        public static void Main() {

            Type test123Type = typeof(Test123<>);
            Type test123Type_int = test123Type.MakeGenericType(typeof(int));
            object test123_int = Activator.CreateInstance(test123Type_int);

            object test321 = Activator.CreateInstance(typeof(Test321));
            PropertyInfo test_prop = test321.GetType().GetProperty("Test");
            test_prop.GetSetMethod().Invoke(test321, new object[] { test123_int });

        }

    }
}

Check this Overview of Reflection and Generics on msdn.

Paolo Tedesco