1

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?

Servy
  • 202,030
  • 26
  • 332
  • 449
Kazaar
  • 33
  • 6
  • 7
    That syntax for generic instantiation requires the type to be known at compile time. You'd need to use some form of reflection. https://msdn.microsoft.com/en-us/library/b8ytshk6.aspx https://msdn.microsoft.com/en-us/library/ms172334.aspx https://msdn.microsoft.com/en-us/library/ms173128.aspx – David Heffernan Jan 30 '15 at 19:19
  • Reflection is an advanced topic which you should leave to experienced programmers. Pick something simpler to play with while learning the language. – Mike Nakis Jan 30 '15 at 19:26
  • Well, thanks Mike but I have to do this :) – Kazaar Jan 30 '15 at 19:29
  • why are you assuming it has an empty constructor? – AK_ Jan 30 '15 at 19:30
  • 1
    http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method – Selman Genç Jan 30 '15 at 19:31

1 Answers1

0

Try:

obj = GetType().GetMethod("RandomObject", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(t).Invoke(null, ...);
afeygin
  • 1,213
  • 11
  • 26