Visual Basic .NET Language Extension methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

Extension methods are methods (Sub or Function) that add functionality to a Type (which may be a Reference Type or a Value Type). These Types may or may not be owned by you.

They may or may not be in the same assembly as the Type they are intended to modify. You can allow an opt-in to your extension methods by isolating them in their own namespace. Or if you prefer you can make them always available by including them in the same namespace as the Type they modify (assuming all the assembly references are in place and correct). See the Entity Framework Core 1.0 project on GitHub for a good example of the opt-in style of extension methods.

Extension methods in VB have a few requirements:

  • Extension methods may only be declared in modules.
  • Extension methods must be decorated with the Extension() attribute.
  • The ExtensionAttribute namespace must be available within your module.
    Imports System.Runtime.CompilerServices
  • The first parameter to the method must be of a type that this method will be attached to.
  • The first parameter of the method will represent the instance that this method operates on. (Equivalent to Me if this were a real instance method).
  • An extension method can be called as a regular method by supplying all parameters if not called on the instantiated object.


Got any Visual Basic .NET Language Question?