Generic extension method with multiple constraints

Posted on Wed 18 January 2012 in Coding

In a .NET project, I was coding an extension method for forms, and for various reasons I needed to call a form method which came from an interface. Instead of coding an ugly type check and subsequent type cast, I was happy to discover that I could simply create a generic extension method and constrain the generic type parameter to be a form and to implement my interface:

<Extension()>
Public Sub DoStuff(Of T As {Form, ISomeInterface})(ByVal form As T)
End Sub

No type casting means less code and less evil! Hooray!

(If you wonder about the odd-looking code, it’s because it’s VB… ;-))