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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With