7

I'm trying to make a Class library with a function to convert binary integers to denary, and vice versa, so that I can import it into another project without having to rewrite the function. It works fine, here's part of the class:

Public Class BinaryDenary
    Public Shared Function ToBinary(ByVal DenaryNumber As Integer) As Integer
        Dim Binary As String = ""
        While DenaryNumber > 0
            If DenaryNumber Mod 2 = 1 Then
                Binary = 1 & Binary
            Else
                Binary = 0 & Binary
            End If
            DenaryNumber \= 2
        End While
        Return CInt(Binary)
    End Function
End Class

I've tested it within the project and it works fine.

ToBinary(3) 'Returns 11
ToDenary(110) 'Returns 6

But - mostly for aesthetic reasons - I'd like to be able to use it like an extension method, so that I can take a variable and do this:

NormalInt.ToBinary(3)

But I can't write extension methods inside of a class. Is there any way of doing this? It's not hugely important, but I like to use extension methods where I can.

Lou
  • 2,200
  • 2
  • 33
  • 66

1 Answers1

17

An extension method written in VB .NET, must be in a Module and be marked with the Extension attribute, something like this:

Public Module BinaryDenary

    <Extension()>
    Function ToBinary(ByVal DenaryNumber As Integer) As Integer
        Dim Binary As String = ""
        While DenaryNumber > 0
            If DenaryNumber Mod 2 = 1 Then
                Binary = 1 & Binary
            Else
                Binary = 0 & Binary
            End If
            DenaryNumber \= 2
        End While
        Return CInt(Binary)
    End Function

End Module

If the module isn't in the same namespace, you should import the namespace where it is used.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
Zach dev
  • 1,610
  • 8
  • 15
  • What is the Namespace? The Module? Do I import it the same way I import a class? – Lou Jul 20 '13 at 10:33
  • Namespaces it's another way to organize your code, read about it here [Understanding Assembly and Namespace](http://msdn.microsoft.com/en-us/library/ms973231.aspx) A module is a logical collection code within an assembly, read about it here [What is a module in .NET?](http://stackoverflow.com/questions/645728/what-is-a-module-in-net) – Zach dev Jul 20 '13 at 12:55
  • So, just to clarify: I should write the functions within a new module in a separate Namespace? And should this be in a separate .vb file? – Lou Jul 20 '13 at 19:18
  • 1
    should or should not, depends on good practices that you apply to your project, you can research and explore about project architecture for more details – Zach dev Jul 22 '13 at 21:54