Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call C# extension methods in VB code

I have a class library with some extension methods written in C# and an old website written in VB.

I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.

I have got all the required Imports because other classes contained in the same namespaces are appearing fine in Intelisense.

Any suggestions

EDIT: More info to help with some comments.

my implementation looks like this

//C# code compiled as DLL
namespace x.y {
    public static class z {
        public static string q (this string s){
             return s + " " + s;
        }

    }
}

and my usage like this

Imports x.y

'...'
Dim r as string = "greg"
Dim s as string = r.q() ' does not show in intelisense
                        ' and throws error : Compiler Error Message: BC30203: Identifier expected.
like image 857
Greg B Avatar asked Oct 17 '08 17:10

Greg B


2 Answers

It works for me, although there are a couple of quirks. First, I created a C# class library targeting .NET 3.5. Here's the only code in the project:

using System;

namespace ExtensionLibrary
{
  public static class Extensions
  {
    public static string CustomExtension(this string text)
    {
      char[] chars = text.ToCharArray();
      Array.Reverse(chars);
      return new string(chars);
    }
  }
}

Then I created a VB console app targeting .NET 3.5, and added a reference to my C# project. I renamed Module1.vb to Test.vb, and here's the code:

Imports ExtensionLibrary

Module Test

    Sub Main()
        Console.WriteLine("Hello".CustomExtension())
    End Sub

End Module

This compiles and runs. (I would have called the method Reverse() but I wasn't sure whether VB might magically have reverse abilities already somewhere - I'm not a VB expert by a long chalk.)

Initially, I wasn't offered ExtensionLibrary as an import from Intellisense. Even after building, the "Imports ExtensionLibrary" is greyed out, and a lightbulb offers the opportunity to remove the supposedly redundant import. (Doing so breaks the project.) It's possible that this is ReSharper rather than Visual Studio, mind you.

So to cut a long story short, it can be done, and it should work just fine. I don't suppose the problem is that you're either using an old version of VB or your project isn't targeting .NET 3.5?

As noted in comments: there's one additional quirk, which is that extension methods won't be found when the compile-time type of the target is Object.

like image 181
Jon Skeet Avatar answered Oct 25 '22 11:10

Jon Skeet


Extension methods are just syntactic sugar for static methods. So

public static string MyExtMethod(this string s)

can be called in both VB.NET and C# with

MyExtMethod("myArgument")
like image 45
ICR Avatar answered Oct 25 '22 10:10

ICR