dotnet / dotnet/vblang

Why does this even compile? (Circular self-initialisation).

Open
#325 8 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
328
Forks
71
PR merge metrics
No merged PRs in 30d

Description

After doing some "Find & Replace" in some code I was working on I wound up with code like this:

```vb
Public Class TestClass
Private ReadOnly SomeFoo As SomeOtherClass = Me.SomeFoo
End Class
```

Strangely enough, that code compiles without a problem and when you try to access the `SomeFoo` field at run-time you get a null reference exception. It's a little hard to spot at first, but the problem is `SomeFoo` is being initialised to the value of `SomeFoo`. **It is being initialised with its own value** which makes no sense logically because it is circular.

The compiler already rejects other circular scenarios such as a class inheriting from itself:

![vs_self_init](https://user-images.githubusercontent.com/20465797/42424128-2875fea0-830f-11e8-80e7-2f3398e834cd.png)

...so is there any reason why circular initialisation of a field is allowed (or even useful)?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.