2

In my code I have the following interface

public interface ILogParser<TParserOptions> { }

I have retrieved all types that use this interface via reflection and I am trying to instantiate them. Normally I would do something along the lines of:

var parser = (ILogParser)Activator.CreateInstance(parserType)

However, this doesn't work when you are dealing with Generics, since you need to know the generic type at the time of casting, which can vary depending on each implemented type.

Is this possible?

KallDrexx
  • 27,229
  • 33
  • 143
  • 254
  • possible duplicate of [How to dynamically create generic C# object using reflection?](http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-object-using-reflection) – BoltClock Sep 21 '11 at 00:06

1 Answers1

1

You can use Type.MakeGenericType on the interface's type to make a specific instance of some object that implements the interface.

Once you have the appropriate type (with the generic type specified), Activator.CreateInstance will work fine.

For example, in the above, you could use:

Type interfaceType = typeof(LogParser<>); // Some class that implements ILogParser<T>
// Make the appropriate type - 
// Note: if this is in a generic method, you can use typeof(T)
Type fullType = interfaceType.MakeGenericType( new[] { typeof(Int32) });

object result = Activator.CreateInstance(fullType);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • the problem is this doesn't give me access to the `IParser` methods, even the non-generic ones. Maybe generics just won't work for this scenario. – KallDrexx Sep 21 '11 at 00:08
  • I don't know the type at compile time. The user selects which parsing engine they want to use, and the system creates it and proceeds with the parsing. I was hoping I could take a subclass of the generic type and use that to pass implementation specific options around, but it's looking like generics won't work for that. – KallDrexx Sep 21 '11 at 00:15
  • `ILogParser<>` is an *interface* -- there's obviously no way to instantiate *that*, regardless of whether it's been fed through `MakeGenericType`. – Kirk Woll Sep 21 '11 at 00:28
  • @KallDrexx: You'd need to know the specific type. Something like MEF can help quite a bit here, though... – Reed Copsey Sep 21 '11 at 00:31
  • Ooooh I didn't think about MEF. I have been wanting to find a good excuse to learn it, maybe this is it. Thanks :) – KallDrexx Sep 21 '11 at 00:50