Home

Problem: Extension methods in a VB query

I can define an extension method in a C# query (see below). However, when I try to do the same thing in a VB query:

Sub Main
    Dim lst As New List(Of Integer)
    lst.ForEach(AddressOf Console.WriteLine)
End Sub

Module Extensions
    <System.Runtime.CompilerServices.Extension> Public Function ForEach(Of T)(src As IEnumerable(Of T), action As Action(Of T, Integer)
        Dim current = 0
        For Each item In src
            action(item, current)
            current += 1
        Next
        Return src
    End Function
End Module

I get BC30617: 'Module' statements can occur only at file or namespace level.

I know I can define the extension method in C# under My Extensions; but this is a one-off, and it makes sense to include it in the query.

This is the corresponding C# query, which compiles and runs successfully:

void Main() {
    var lst = new List<int>();
    lst.ForEach(Console.WriteLine);
}

// Define other methods, classes and namespaces here
public static class Extensions {
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> src, Action<T, int> action) {
        var current = 0;
        foreach (var item in src) {
            action(item, current);
            current += 1;
        }
        return src;
    }
}

Comments

  • You can end the UserQuery class, include the module and then start a dummy class to make up for the 'End Class' statement.

    Sub Main
      Dim lst As New List(Of Integer)
      lst.ForEach(AddressOf Console.WriteLine)
    End Sub
    
    End Class ' UserQuery
    
    Module Extensions
    
      <System.Runtime.CompilerServices.Extension>
      Public Function ForEach(Of T)(src As IEnumerable(Of T), action As Action(Of T, Integer))
        Dim current = 0
        For Each item In src
          action(item, current)
          current += 1
        Next
        Return src
      End Function
    
    End Module
    
    Class Dummy ' Otherwise you'll get this error: BC30460 'End Class' must be preceded by a matching 'Class'.
    
Sign In or Register to comment.