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.
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.
Extension methods enable developers to add custom functionality to data types that are already defined without creating a new derived type. Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With