I think I've encountered a similar problem: VB.Net is quite happy to compile on through extension methods and leave them to be inferred at run-time if Option Strict
is off.
However, VB.Net really doesn't seem to like extension methods on basic types. You can't extend Object
and it can't resolve it if you do:
C#
namespace NS
...
public static class Utility {
public static void Something(this object input) { ...
public static void Something(this string input) { ...
}
// Works fine, resolves to 2nd method
"test".Something();
// At compile time C# converts the above to:
Utility.Something("test");
However this goes wrong in VB.Net:
Option Infer On
Option Explicit On
Option Strict Off
Imports NS
...
Dim r as String = "test"
r.Something()
That compiles without error, but at run time fails because Something
is not a method of String
- the compiler has failed to replace the syntactic sugar of the extension method with the the static call to Utility.Something
.
The question is why? Well unlike C#, VB.Net can't handle any extension to Object
! The valid extension method in C# confuses the VB.Net compiler.
As a general VB.Net rule, I'd avoid using extension methods with any of the basic .Net types (Object
, String
, Integer
, etc). You also have to be careful with Option Infer
as while it's on by default in Visual Studio it's off by default for command line compiles, VBCodeProvider
, and possibly in web sites (depending on your web.config). When it's off everything in VB.Net is considered to be an Object
and all extension methods will be left until run time (and will therefore fail).
I think Microsoft really dropped the ball when they added extension methods to VB.Net, I think it was an afterthought to try (and fail) to make it consistent with C#.