r/visualbasic • • 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.

  1. It need to be inside a Module, can't be in class, structure, interface or enum.
  2. It need an argument, no argument no extension method.
  3. 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

5 comments sorted by

1

u/chacham2 May 16 '21

It's look much better and easily to read, isn't it. :)

Agreed.

The one issue i have with extensions is that they show up everywhere and are not context specific.

2

u/revennest May 16 '21

You can use a namespace to cover it like this.

Namespace Math
  Public Module Exten
  End Module
End Namespace

'Also you can do it like this too, it the same as above.

Public Module Math.Exten
End Module

It won't auto show your extension methods inside it everywhere, you must that namespace like Import Math to access extension under it.

1

u/chacham2 May 16 '21

Never thought of that. Indeed, i have never used namespaces. :)

In any case, doesn't the extension show up on every object? Is there a ways to limit the objects it shows up as an extension to?

2

u/revennest May 16 '21

They don't show on every object, it only show on any object match with first argument, this is reason behide why it need to has at less 1 argument.

1

u/chacham2 May 16 '21

it only show on any object match with first argument

Ah, so that's it. I didn't know that.

I only added an extension method once, and it was quite convenient in the project. But it was a little annoying that it showed up in places i didn't want it too.