C# Extension Method on Type With Generic Type Argument
This is not exactly like you asked, but maybe it will suffice.
internal class Program
{
static void Main(string[] args)
{
var fizzHandler = new Fizz();
var context = new Context();
Handle<Bar>.With(fizzHandler, context);
}
}
public class Bar { }
public class Event<T> { }
public class Fizz : Event<Bar> { }
public class Context { };
public static class Handle<T>
{
public static void With(Event<T> e, Context c)
{
//do your stuff
}
}
Why not do something a bit more idomatic, where you could use generic constraints to enforce the rules:
public static class SubscriptionManager
{
public static void SubsribeTo<TSub,TEvent>( Context context )
where TEvent : Event<TSub>
{
/// you code...
}
}
The calls would look like:
SubscriptionManager.SubsribeTo<Bar,Fizz>( context );
The constraint where TEvent : Event<TSub>
ensures the relationship between the event and subscription type that you desire. It's also preferrable in my book to an extension method on the class Type
- because that tends to clutter intellisense. Type
is used in many situations, and having spurious methods appear in Intellisense on all instances of Type
tends to be confusing. It's also non-obvious for consumers of library that this is the way to "subscribe" - unless they've actually seen a code example of it.