Search code examples
c#genericsgeneric-method

Get type of property in generic method


I have method:

static T RandomObject<T> (...) {
var tmp = Activator.CreateInstance<T>();
...
   foreach (PropertyInfo info in tmp.GetType().GetProperties()){
   ...
   }
}

And if class T have object properties I want to generate them random too, so what I do is:

var t = info.PropertyType;
obj = RandomObject<t>(...);

And then I get:

The type or namespace name t could not be found (are you missing a using directive or an assembly reference?)

Any idea to solve this problem?


Solution

  • Try:

    obj = GetType().GetMethod("RandomObject", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(t).Invoke(null, ...);