Why can't VB.Net find an extension method on an interface?
.net, extension-methods, vb.net
Solution
With Option Infer Off, this code...
Dim something = Me.SomethingManager.GetSomething(key)
Dim result = something.ExtensionMethod("extra")
...is the same as...
Dim something As Object = Me.SomethingManager.GetSomething(key)
Dim result As Object = something.ExtensionMethod("extra")
Since `something` is of type `Object`, it can't find the extension method, since it isn't defined on type `Object`.
Now, if you set `Option Infer On`, you will get the same results as with C#'s `var` keyword. Types will be automatically inferred. Note that this could also break existing code, but it can be enabled for a specific file, like `Option Strict`.
The best practice would be to set both `Option Strict` and `Option Infer` to On.
Problem
I have a C# library that has an extension method, something like: ``` public interface ISomething { ... } public class SomethingA : ISomething { ... } public class SomethingB : ISomething { ... } public static class SomethingExtensions { public static int ExtensionMethod(this ISomething input, string extra) { } } ``` The extension works fine if called from C#, but has an issue if called from an external VB.Net application: ``` Dim something = Me.SomethingManager.GetSomething(key) Dim result = something.ExtensionMethod("extra") ``` This compiles fine but throws an exception at run time: Public member 'ExtensionMethod' on type 'SomethingB' not found. If the VB.Net is changed to explicitly make the type the interface it works: ``` Dim something as ISomething = Me.SomethingManager.GetSomething(key) Dim result = something.ExtensionMethod("extra") ``` Why? Why does the extension method work on the interface but not the class that implements it? Would I have the same issue if I used a subclass? Is VB.Net's implementation of extension methods incomplete? Is there anything I can do in the C# library to make VB.Net work without the explicit interface?