What is the use of field initialisers in .NET(apart from readability)?

Viewed 117

I am just trying to learn about field initializers. I ran into the error - field initializers cannot use non static field, method or prop. While hunting an answer for this I came across THIS post.

Most up voted answer, to the post, suggests that 'this' doesn't exist until the constructor is called. Does anyone know why it is that way? Why couldn't 'this' have existed before field initializers are invoked?

In my mind, coming from a C/C++ background, 'this' is merely just a block of memory allocated on the heap. And it has to exist before any member of 'this' can be assigned a value. (So it definitely exists before field initializers).

3 Answers

If this was available inside the initializers, it means you could access the values of other fields that have not had their initializers run yet (or even potentially the field you are currently initializing!). Consider:

class Foo
{
    private int a = this.b + 1;
    private int b = this.a + 2;

    public Foo()
    {
        Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}

To avoid breaking memory safety and giving you access to uninitialized memory, these fields would have to be initialized twice, first with default values, then with the result of calling the initializer.

It's not unsolvable, but it's kind of weird. Hiding the current instance until all of its field initializers have finished running avoids this situation where you can see a partially-initialized object.

Related