none
Extension Method does not show up RRS feed

  • Question

  • Hey

    I am trying to get an extension method working, but without success.

    I have the following basic extension

    Imports System.Runtime.CompilerServices
    Namespace Extensions
        <Extension()>
        Module ConvertListExtension
            Public Function ToListOf(Of T, R)(Data As List(Of R)) As List(Of T)
                Dim locReturnList As New List(Of T)
                Return locReturnList
            End Function
            
        End Module
    End Namespace

    Now in my class, I try the following:

    Imports OPT_Studio.Extensions
    Public Class MyClass
    
    Private Sub ConvertList
       Dim locList As New List(of AnotherClass)
       locList.ToList... 'Here the extension does not show up
      
    End Sub
    

    I already saved the project and rebuild it, but without any success.

    (Please don't give me information about AutoMapper - I know, this is something, what can be used, but I try to make my own logic)

    THX

    Saturday, September 22, 2018 4:05 PM

Answers

  • Found the solution now.

    There where two errors in my code.

    1) The Annotation Extension must be up of the function, and not on top of the module

    2) The first generic "T" must be the passed data.

    So this means, it the code looks like this (and works now)

    <Extension()>
    Public Function ToListOf(Of T, R)(ByVal Data As List(Of T)) As List(Of R)

    • Marked as answer by Zero-G. _ Saturday, September 22, 2018 5:28 PM
    Saturday, September 22, 2018 5:28 PM

All replies

  • Hello,

    does not show up

    Most likely problem is in class and method declaration - for creating an extension method require static class on the first level (this Ok) and static method (C# terminology).


    Sincerely, Highly skilled coding monkey.

    Saturday, September 22, 2018 4:21 PM
  • Hey

    THX, but in VB this isn't the case.

    In VB.NET you have declare it as a Module (not as a class) and a module can not have Shared (What is the equivalent to static) methods.

    So, in other words. - This isn't the problem...

    Saturday, September 22, 2018 5:00 PM
  • Found the solution now.

    There where two errors in my code.

    1) The Annotation Extension must be up of the function, and not on top of the module

    2) The first generic "T" must be the passed data.

    So this means, it the code looks like this (and works now)

    <Extension()>
    Public Function ToListOf(Of T, R)(ByVal Data As List(Of T)) As List(Of R)

    • Marked as answer by Zero-G. _ Saturday, September 22, 2018 5:28 PM
    Saturday, September 22, 2018 5:28 PM