VB.NET Extension Methods

when I apply the tag above my methods, I get an error

The type System.Runtime.CompilerServices.Extension is not defined.

Here is my example

<System.Runtime.CompilerServices.Extension()> _ Public Sub test() End Sub 

Where am I going wrong?

Edit ~ Directly from the MSDN article here , same error

 Imports System.Runtime.CompilerServices

 Module StringExtensions
      _
   Public Sub Print (ByVal aString As String)
         Console.WriteLine (aString)
     End sub

 End module

I am using Visual Studio 2008 and 3.5 Framework in my project.

Solution ~ The project was on the 2.0 Framework. Changed to 3.5 and it works.

+7
extension-methods
source share
4 answers

What version of the .NET Framework is the IDE pointing to?

In addition, at first glance, the syntax of the extension method seems incorrect.

The code is incomplete. Please put the using statements in the example so that someone uses the code and compiles it - to reproduce the error.

+8
source share

You should only receive this error if one of the following values ​​is true:

  • You are not using VS 2008 - support for the extended method was added in VS2008
  • There is no reference to System.Core.dll in your code - also added in VS2008

Can you check both of them? My guess is that you are trying to use VS2005 to create an extension method. If so, unfortunately, it is not supported.

+3
source share

Use this ...

System.Runtime.CompilerServices.ExtensionAttribute

Could not find anything called Extension in the namespace you mentioned.

0
source share

I would add a namespace to the import, so you do not need to enter it every time:

 Imports System.Runtime.CompilerServices <Extension()> _ Public Sub Test(ByVal Value As String) End Sub 

After you import it, you can simply add the extension to the top of each method, and not just everything.

As Shakhkalpesh said, your extension method is incomplete, you will need to add the type that you want to expand (see the first code pair). I just had a game, and I found that if you do not specify a type that will expand as a parameter, the compiler will throw an error.

0
source share

All Articles