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.
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.
You should only be getting this error if one of the following are true
- You are not using VS 2008 - Extension Method support was added in VS2008
- 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.
Couldn't find anything called Extension in the namespace you mentioned.
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.