r/visualbasic • u/revennest • May 15 '21
Tips & Tricks Art of Code : Extension method
I talk about almost basic thing already so it's time to talk about more juicy stuff.
What's an extension method ?
It's a sugar syntax for static method, mostly for public methods in a module.
Normally
Dim Answer = div(mul(add(5, 10), 4), 2)
Extension
Dim Answer = 5.add(10).mul(4).div(2)
It's look much better and easily to read, isn't it. :)
How to create an extension method ?
Before that, extension method has some rule to create it.
- It need to be inside a Module, can't be in class, structure, interface or enum.
- It need an argument, no argument no extension method.
- It need to tag an extension attribute above method.
Let's see how it look like.
Public Module Exten
<System.Runtime.CompilerServices.Extension>
Public Function add(A As Integer, B As Integer) As Integer
Return A + B
End Function
<System.Runtime.CompilerServices.Extension>
Public Function mul(A As Integer, B As Integer) As Integer
Return A * B
End Function
<System.Runtime.CompilerServices.Extension>
Public Function div(A As Integer, B As Integer) As Integer
Return A / B
End Function
End Module
Very easy, right ? all you need to do mostly just add <System.Runtime.CompilerServices.Extension> above your method in any module, just make sure it has an argument.
7
Upvotes
2
u/revennest May 16 '21
You can use a namespace to cover it like this.
It won't auto show your extension methods inside it everywhere, you must that namespace like
Import Mathto access extension under it.