A field initializer cannot reference the non-static field, method, or property?

Personally I’d just initialize the fields in a constructor:

public class Service
{
    private readonly DinnerRepository repo;
    private readonly Dinner dinner;

    public Service()
    {
        repo = new DinnerRepository();
        dinner = repo.GetDinner(5);
    }
}

Note that this isn’t the same as the code you show at the bottom of the question, as that’s only declaring local variables. If you only want local variables, that’s fine – but if you need instance variables, then use code as above.

Basically, field initializers are limited in what they can do. From section 10.5.5.2 of the C# 4 spec:

A variable initializer for an instance field cannot reference the instance being created. Thus it is a compile-time error to reference this in a variable initializer, because it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

(That “thus” and “therefore” looks the wrong way round to me – it’s illegal to reference a member via a simple-name because it references this – I’ll ping Mads about it – but that’s basically the relevant section.)

Leave a Comment