1 Replies - 2163 Views - Last Post: 04 March 2014 - 02:58 PM

#1 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,462
  • Joined: 29-May 08

Tip: Extension Methods use Functions over Sub

Post icon  Posted 04 March 2014 - 12:59 PM

Tip: Extension Methods use Functions over Sub

Let's presume that the System.Runtime.CompilerServices namespace has been imported.

Public Module Exts
  <Extension>
  Public Sub SetBGcolor(c As Control, bg As Drawing.Color) 
    c.BackgroundColor = bg
  End Sub
  <Extension>
  Public Sub SetFGcolor(c As Control, fg As Drawing.Color) 
    c.ForegroundColor = fg
  End Sub
End Module



MyLabel.SetBG( Color.Blue )
MyLabel.SetFG( Color.Pink )



Using Functions

Public Module Exts
  <Extension>
  Public Function SetBGcolor(c As Control, bg As Drawing.Color) As Control
    c.BackgroundColor = bg
    Return c
  End Function 

  <Extension>
  Public Function SetFGcolor(c As Control, fg As Drawing.Color) As Control
    c.ForegroundColor = fg
    Return c
  End Function 

End Module



Why prefer to use a function?
If you return something. For example the thing you've been working on in the method. Which allows us to chain methods together, also know as Fluent style.
Also VB.net lets you call a Function without having to store the returned value in a variable.
Just use the function (for it's side-effects) and discard the result.
myLabel.SetBGcolor( Color.Blue ).SetFGcolor( Color.Pink )




You may have seen this before via the LINQ extension methods.
Spoiler

This post has been edited by AdamSpeight2008: 05 March 2014 - 01:17 PM


Is This A Good Question/Topic? 1
  • +

Replies To: Tip: Extension Methods use Functions over Sub

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3459
  • View blog
  • Posts: 11,711
  • Joined: 12-December 12

Re: Tip: Extension Methods use Functions over Sub

Posted 04 March 2014 - 02:58 PM

Thank you.

I suppose Functions are preferred because they are closer to the MSIL? I'll guess also that even if we use a Sub it is effectively translated into a Function, or something equivalent in the MSIL?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1