Consider the following:
Public Module Extensions
<Extension()> _
Public Sub Initialize(ByRef Target as SomeClass, ByVal SomeParam as Something )
...
Target = SomethingElse
end Sub
End Module
Class SomeClass
...
sub New(ByVal SomeParam as Something )
Me.Initialize(SomeParam)
end sub
sub New()
end sub
End Class
'Case 1: Doesnt Work...why????:
Dim foo as new SomeClass(SomeParam) 'foo remains uninitialized
'Case 2: Does Work:
Dim foo as new SomeClass()
foo.Initialize(SomeParam) 'foo is initialized
Question:
Why is Case 1 failing to initialize the object as expected?
The problem here is that VB.Net supports multiple ways of using ByRef parameters. I did a detailed explanation of the types in a recent blog entry
What’s happening here is that
Meis not an assignable value. So instead of passingMeas a byRef parameter, the VB compiler will instead pass a temporary. This is loosely known as “Copy Back ByRef”. It effectively generates the following codeThere is no way to work around this in the case of
Mebecause it’s not assignable. In the case of the local variablefoothough this works as expected becausefoois a valid ByRef value.