0

I'm looking to convert the string name of a class to a class, then pass that class name to a method which accepts <T>:

var objectList = _reader.GetObjects<MyClassName>();

and the method I'm calling is:

public List<T> GetObjects<T>() where T:new() {

}

Do you know how this can be done? I've tried:

var type = Type.GetType(MyClassName);
var yourObject = Activator.CreateInstance(type);

var objectList = _reader.GetObjects<yourObject>();

but that doesn't work, I get the error message 'yourObject is a variable but is used like a type'

It does work if I use an actual class name.

Any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
thegunner
  • 6,883
  • 30
  • 94
  • 143

1 Answers1

-2

The .NET generic syntax <T> is resolved at compile time, so you cannot do directly what you want to do. If you do not have control of your reader class, then you can call it using reflection as described in How do I use reflection to call a generic method?

However, if you are writing the reader class, then I prefer doing something like this:

public List<T> GetObjects<T>() where T : class
{
    return GetObjects(typeof(T)).Cast<T>();
}

public List GetObjects(Type type)
{
    ...
}

Now, if you only have a string at runtime, you can call the second form like this:

var objectList = _reader.GetObjects(Type.GetType(MyClassName));

Of course, this assumes you have control over your 'reader' class.

Community
  • 1
  • 1
Dave Tillman
  • 589
  • 4
  • 13
  • It's definitely possible to invoke generic methods via reflection. – Rob Nov 28 '16 at 01:06
  • I updated the post to reflect using the possibility of using reflection. I think my answer has value if the OP has control of the reader class. – Dave Tillman Nov 29 '16 at 00:57