C# .NET -- Implied Generics in Extension Methods
A Really Cool Way to Raise Events
I have previously written an article on extensions methods, which included some information about using generics with extension methods. Since that time, I have stumbled across something I did not previously realize:
If the compiler can figure out the generic type from one of the parameters passed into the extension method, you do not have to explicitly specify the generic type.
So what exactly does that mean? Consider the example below.
public static class EventHandlerExtensions
{
public static void XOn<TEventArgs>(
this EventHandler<TEventArgs> eventDelegate,
object sender,
TEventArgs e)
where TEventArgs : EventArgs
{
if (null == eventDelegate)
{
return;
}
try
{
eventDelegate(sender, e);
}
catch(Exception ex)
{
// I obviously would not eat the exception, but might want to log something
// before propagating the error.
throw;
}
}
}
Given that example extension method above, XOn<TEventArgs>()
, the compiler is able to figure out the type TEventArgs
based on what was passed in for the e
parameter. That means there are both explicit and implicit ways to make the call. Consider the example below, and look at the RaiseEventSamples()
method to see both.
public class HelloWorldEventArgs : EventArgs
{
public string HelloWorld { get; private set; }
public HelloWorldEventArgs(string world)
{
HelloWorld = "Hello " + world;
}
}
public class MyClass
{
public event EventHandler<HelloWorldEventArgs> HelloWorld;
public void RaiseEventSamples()
{
// The type for TEventArgs can be explicitly specified as HelloWorldEventArgs
HelloWorld.XOn<HelloWorldEventArgs>(this, new HelloWorldEventArgs("World"));
// The type for TEventArgs can be implied from the HelloWorldEventArgs object
HelloWorld.XOn(this, new HelloWorldEventArgs("World"));
}
}
I think I have found my new favorite way for raising events! Well, at least when the event delegate is one of the EventHandler<TEventArgs>
events. If you wanted to do the same for the INotifyPropertyChanged.PropertyChanged
event, for example, you would have to write a special extension method since that PropertyChanged
event delegate is a PropertyChangedEventHandler
instead of a EventHandler<PropertyChangedEventArgs>
.
Programmer, Engineer