Can I make an Extension method for all the subclasses of System.Object
(everything)?
Example:
<Extension>
Public Function MyExtension(value As Object) As Object
Return value
End Function
The above functions won't work for object instance:
Dim myObj1 As New Object()
Dim myObj2 = myObj1.MyExtension()
The compiler does not accept it, is the problem in my computer? :)
UPDATE
The problem seems to occur only in VB, where members of object are looked-up by reflection (late-bound).
UPDATE AFTER ANSWERED
FYI, as vb has an advantage that C# lacks that is, members of imported Modules are imported to the global scope so you can still use this functions without their wrapper:
Dim myObj2 = MyExtension(myObj1)
Sure you can, though you might want to be sparing about what you do here so as not to clutter every object. An extension method I like using for Object is a method called IsIn() that functions similarly to the SQL IN() statement. It's nice to say things like:
EDIT -
Added implementation of IsIn() extension method below to help commenter.
It seems like not supporting Extension methods on Object was a design decision in VB.
http://blogs.msdn.com/b/vbteam/archive/2007/01/24/extension-methods-and-late-binding-extension-methods-part-4.aspx
You can not directly write an extension method for Object, but using generics you can achieve the same result:
Note that you can call this as an extension method on everything except things that are declared to have the type Object. For those, you have to either call it directly (fool proof) or call via casting (which could fail, as there is no univesal interface, so somewhat chancy).
jmoreno's answer cannot be used with
Option Strict On
– it throws error:It needs context switch from class to extension module:
If you do too many extensions on object intellisence might become less useful, but it's perfectly valid.
Here's an example of an extension method on object for object information:
http://www.developer.com/net/csharp/article.php/3718806/NET-Tip-Using-Extension-Methods.htm
See this question I asked some time ago. Basically, you can extend
Object
in VB.NET if you want; but for backwards compatibility reasons, no variable declared asObject
will be able to use your extension method. This is because VB.NET supports late binding onObject
, so an attempt to access an extension method will be ignored in favor of trying to find a method of the same name from the type of the object in question.So take this extension method, for example:
This extension method could be used here:
But not here:
Ask yourself why extension methods don't work on
dynamic
variables in C#, and you'll realize the explanation is the same.