views:

89

answers:

1

actually I don't know whether they should work

I made a library in C# and I've been told by people that one of mine methods don't work in VB.NET as extension http://valueinjecter.codeplex.com/Thread/View.aspx?ThreadId=227498

this is the method:

public static PropertyDescriptorCollection GetProps(this object o)
{
   return GetProps(o.GetType());
}
+4  A: 

In general C# extension methods work just fine in VB.Net and vice versa. The one exception is when the this parameter is explicitly typed to Object. For legacy reasons VB.Net does not support the use of extension methods on references that are typed to Object.

The reason why is has the potential to cause code to silently recompile with different semantics. VB.Net (and C#) took the stance that importing a namespace which contains extension method(s) should not cause a silent rebind of existing code to the extension method. If VB.Net allowed extension methods on Object then it would be possible for late bound calls to silently rebind to the extension method and hence change the code.

For example. Consider the following written before your extension method.

Dim local As Object = ... 
local.GetProps() ' This is a late bound call

If VB.Net allowed the GetProps extension method to be defined on Object then simply importing your namespace would change the meaning of GetProps from late bound to an extension method call.

JaredPar
Wouldn't it be possible for the VB.Net runtime binder to consider extension methods if the specified method isn't part of the object's class? Or are extension methods not available at runtime?
Gabe
@Gabe is it possible for the runtime binder to consider extension methods ... yes. It would require several changes (including passing all of the imported namespaces as part of the late bound call). But it could be made to work. The problem though is it would create unpredictable behavior because the set of considered methods for late binding would be changed by what DLL/EXEs were loaded in the process. This means a simple change in DLL load order could change how `GetProps` was interpreted. That's a very scary prospect
JaredPar
In this case, the compiler can resolve `GetProps` as an extension method and pass only that one to the runtime binder for use as a fallback. While it might be nice (and/or scary) to have extension methods dynamically resolved at runtime, it doesn't seem necessary to get the behavior the OP is expecting.
Gabe
Just to state the obvious, the OP can still call `PropertyDescriptorCollection.GetProps(x)`
Henk Holterman
@Gabe, a feature which produces unpredictable behavior is a bad one.
JaredPar