Why is `this` not available in C# 6.0 Auto Property Initialization?

I have the following code class:

public class Foo
{
    public Nested Bar { get; } = new Nested(this);

    public class Nested
    {
        public Nested(Foo foo)
        {
            foo.DoSomething();
        }
    }

    private void DoSomething()
    {

    }
}

However, I get this compile error:

Keyword 'this' is not available in the current context

I can fix it by simply not using Auto-Property Initializer, and explicitly move it into a constructor instead:

public Nested Bar { get; }

public Foo()
{
    this.Bar = new Nested(this);
}

Why is it so? Isn't Auto-Property Initializer actually translated into constructor code in IL?

Jon Skeet
people
quotationmark

Why is it so? Isn't Auto-Property Initializer actually translated into constructor code in IL?

The rules for automatically implemented property initializers are the same as those for field initializers, for the same reason. Note that property initializers are executed before base class bodies, just like field initializers - so you're still in the context of a "somewhat uninitialized" object; more so than during a constructor body.

So you should imagine that the property is being converted into this:

private readonly Nested bar = new Nested(this); // Invalid

public Nested Bar
{
    get { return bar; }
}

In short, this restriction is to stop you from getting yourself into trouble. If you need to refer to this when initializing a property, just do it manually in a constructor, as per your second example. (It's relatively rare in my experience.)

people

See more on this question at Stackoverflow