Using extension methods from the constructor of the object, where "Me" is the ByRef target

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 unable to initialize the object as expected?

+4
source share
1 answer

The problem is that VB.Net supports several ways to use ByRef parameters. I explained the types in detail in a recent blog post

What happens here is that Me not an assignable value. Therefore, instead of passing Me as a byRef parameter, the VB compiler instead transmits temporary information. It is loosely called "Copy Back ByRef". It efficiently generates the following code

 Dim temp = Me Initialize(temp, SomeParam) 

There is no way around this in the case of Me , because it cannot be assigned. In the case of the local variable foo , although this works as expected, because foo is a valid ByRef value.

+4
source

Source: https://habr.com/ru/post/1300681/


All Articles