Here’s a little something I discovered in vb.net which I cannot figure out, I’ve just got a form with a treeview on it and then the following:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
treeTest.Nodes.Add("a")
treeTest.Nodes(0).Test()
End Sub
Test is an extension method:
Imports System.Runtime.CompilerServices
Public Module ExtModule
<Extension()>
Public Sub Test(ByRef node As TreeNode)
End Sub
End Module
If I use ByRef then my treeview looks like:

And with ByVal I get:

This seems totally backwards, if I’m simply sending a reference why is the node appearing twice, while if I make a copy it only appears once?
Okay, I’ve worked out some of what’s going on.
It’s got relatively little to do with extension methods per se. It’s more about how VB handles
ByRefin general, and some odd behaviour ofTreeView.Nodesby the looks of it.In particular, you’ll get the exact same behaviour if you change this:
to:
… even if you remove the
ExtensionAttribute.Here’s some C# code which demonstrates the same effect, without using
refparameters or extension methods at all:The important lines are these ones:
When your empty extension method has a
ByRefparameter, your code is equivalent to the above C# code – because VB fakes “real”ByRefbehaviour by using a temporary variable and then assigning back to the original property.When your empty extension method has a
ByValparameter, your code is just equivalent to:… and that doesn’t create a second node.