Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET Extension Methods

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

Type System.Runtime.CompilerServices.Extension is not defined.

Here is my sample

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

End Sub

Where am I going wrong?

Edit ~ Straight from the MSDN Article here, the 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 2.0 Framework. Changed to 3.5 and it works.

like image 810
Saif Khan Avatar asked Dec 02 '08 01:12

Saif Khan


3 Answers

What version of .net framework the IDE is pointing towards?

Also, at first glance the syntax of extension method looks incorrect.

The code is incomplete. Please put the using statements in the example for anyone to use the code and compile it - to reproduce the error.

like image 116
shahkalpesh Avatar answered Sep 24 '22 19:09

shahkalpesh


You should only be getting this error if one of the following are true

  1. You are not using VS 2008 - Extension Method support was added in VS2008
  2. Your code does not have a reference to System.Core.dll - Also added in VS2008

Can you check both of these? My supsicion is that you are attempting to use VS2005 to create an extension method. If this is the case, it is unfortunately not supported.

like image 20
JaredPar Avatar answered Sep 26 '22 19:09

JaredPar


I would add the namespace to the imports so you don't have to type it every time:

Imports System.Runtime.CompilerServices

<Extension()> _
Public Sub Test(ByVal Value As String)

End Sub

Once you have it in your imports you can just add Extension to the top of every method instead of the whole thing.

As shahkalpesh said you extension method is incomplete you will need to add the type you want to extend(see code first parm). I just had a play and found that if you don't supply a type to extend as a parameter the complier will throw an error.

like image 35
Nathan W Avatar answered Sep 24 '22 19:09

Nathan W