Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does VB not prevent the use of "Me" in field initialization like C# does with "this"?

Tags:

c#

vb.net

clr

In VB you can have this:

Class One
    Private myTwo As Two = New Two(Me)
End Class

Class Two
    Sub New(withOne As One)

    End Sub
End Class

But in C#, you can't do this:

class One
{
    private Two myTwo = new Two(this);
}

class Two
{
    public Two(One withOne)
    {

    }
}

Because you get an error "Keyword 'this' is not available in the current context".

I found this question/answer which quotes the C# language specification section 7.6.7:

7.6.7 This access

A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor. ... (specifics omitted) ... Use of this in a primary- expression in a context other than the ones listed above is a compile-time error. In
particular, it is not possible to refer to this in a static method, a static property
accessor, or in a variable-initializer of a field declaration.

Furthermore, this question covers it (although, in my option, does not sufficiently answer it), and Oblivious Sage's answer to my question here explains why -- because it's bug-preventing feature.

Why was this feature left out of VB?

like image 773
rory.ap Avatar asked Dec 10 '14 18:12

rory.ap


1 Answers

As described in this question, the difference is that constructors run before field initializers in VB.NET but after field initializers in C#. Therefore in VB.NET Me is a valid reference when the initializers run, but in C# this is not yet a valid reference when they run.

Per Eric Lippert C# did it that way so that they could guarantee that readonly fields were always initialized before they could be referenced.

I didn't see it explicitly stated anywhere, but if I had to guess they noticed that flaw in VB.NET while C# was still being developed; they then felt that it was a big enough problem to be worth fixing in C# but not a big enough problem to make a breaking (and probably extensive) change to VB.NET.

like image 156
Oblivious Sage Avatar answered Nov 05 '22 08:11

Oblivious Sage