Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Extension methods in Visual Basic

2011-06-02

Extension methods is a well known concept in C#. The idea is that you can add methods to a type without inheritance, as described here.

Visual Basic doesn’t have any linguistic support for extension methods, but it can be done thanks to a method attribute. There are some rules for doing this. You must declare your sub or function in a standard module, not a class. You must have at least one parameter, and that parameter is the type you are extending. Any other parameters will be parameters in your function. Finally, your sub or function must have the System.Runtime.CompilerServices.Extension attribute.

So if you want to add a function that takes no parameters to the Integer type, you will have to define a function that takes one parameter, an Integer. If you want to add a function that takes one parameter, you will have to define a function that takes two parameter, the first must be an Integer and the second (who will serve as the first parameter in your function) can be of any type you like.

Public Function DoubleValue(ByVal I As Integer) As Integer
   Return I * 2
End Function

Remember, the code must be written in a standard module.

The last thing that you have to do, is to add the attribute.

<System.Runtime.CompilerServices.Extension()>
Public Function DoubleValue(ByVal I As Integer) As Integer
   Return I * 2
End Function

(The above code is VBx syntax. For older Visual Basic versions, add a blank followed by an underscore to the attribute line.)

Now you can call the DoubleValue function from any Integer, in this case 5:

Console.WriteLine(5.DoubleValue())

The output will of course be 10.

Categories: VB.NET

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips