Roy Osherove

View Original

Representing void methods with generic delegates

Generics are cool. Learn about them.
I want to talk about a specific query that I had which right now I can only guess the answer.
To begin, here's the scenario.
You can create a Generic Delegate to point to a method you want to execute. For example this simple method :
 
void myMethod(int number)
 
you could create a generic delegate:
 
delegate void invokeDelegate<T>(T input)
 
can invoke it like this: invokeDelegate<int> invoker = myMethod;
(I'm using the new c# 2.0 syntax that allows me to create an "inferred delegate" instead of writing "new invokeDelegate<int>(myMethod)" )
 
it even cool if the method had a return type like this:
 
bool myMethod(int number)
 
you could create a generic delegate:
 
delegate RET invokeDelegate<T,RET>(T input)
and invoke it thusly:
invokeDelegate<int,bool> invoker = myMethod;
 
but how do you take the delegate I've just written and apply it to the *first* method which returns a void? Turns out you can't, at least from my poking around. The more I thought about it the more it makes sense.
If you allow a "void" type to be used as generic type parameter, it is implied that this parameter can be used not only as a return value but as a parameter to the generic function/delegate itself. Here's what someone *could* write if this was possible:
 
delegate void invokeDelegate<T,RET>(T input,RET moreinput)
 
assuming someone does this (if the compiler allowed it):
invokeDelegate<int,typeof(void)> invoker = myMethod;
it would have to implicitly mean that there's a method somewhere looking like this:
 
void myMethod(int number,void IhaveNoIdeaWhatThisIs)
 
which means, in essence, that to represent all method signatures you'd always need at least two generic delegates, one void and one with a generic return value.
That's just my line of thinking, but I'd love for someone from MS to comment on this.