I was wondering if a C# extension method of some class could act as an implementation of interface? What do I have:
An iterface:
public interface IEventHandler
{
void Notify(SEvent ev, IEventEmmiter source);
}
A class that implements it:
class Sim : IEventHandler
{
/*public void Notify(SEvent ev, IEventEmmiter source)
{
Console.WriteLine("Got notified: " + ev.Name);
}*/
}
And a class that contains the extension method:
public static class ReflectiveEventDispatcher
{
public static void Notify(this IEventHandler handler, SEvent ev)
{
if (handler.GetType().GetMethod("Handle" + ev.Name) != null)
{
// C# WTF?
object[] prms = new object[0];
prms[0] = ev;
handler.GetType().GetMethod("Handle" + ev.Name).Invoke(handler, prms);
}
else
{
throw new System.NotImplementedException("This object doesn't have appropriate handler methods for event " + ev.Name);
}
}
}
Now, I want to have various classes with IEventHandler interface and the interfaces' implementation should be fulfilled by the extension method.
If that's not possible, is it possible to define the Notify explicitly and then just forward the call to the extension method?
The code above is basically a multiple inheritance hack. Is it possible to emulate this behaviour by any (other) means?
(I hope this makes sense, I'm used to Ruby and this is giving me really hard time. Oh, how do I miss you, my dear mixins...)
Call forwarding solved it pretty well:
public void Notify(SEvent ev)
{
ReflectiveEventDispatcher.Notify(this, ev,);
}
No, Extension methods can not act as implementation for an interface. Extensions methods are just syntactic sugar for a static method taking an instance of that class as the first parameter, thus not being a member of the specific class, which is a requirement for implementing an interface.