0

I thought the new C# 6.0 property initializers like this.

public MyType MyProperty { get; } = new MyType(OtherProperty);

was the equivalent of this

private MyType _myVariable;
public MyType MyProperty { get { return _myVariable ?? _myVariable = new MyType(OtherProperty); } }

(that OtherProperty is available as part of the instance, not limited to being static)

But in the above first I get "field initializers cannot reference non-static field". Am I doing it wrong, or are property initializers just as limited as

public readonly MyType MyVariable = new MyType(NeedsStaticReference);
4
  • Possible duplicate of Field initializer cannot reference non-static field Commented Jun 21, 2018 at 8:49
  • 1
    @PhilMasterG It is not, I am asking about property intializers which are new in C# 6.0 Commented Jun 21, 2018 at 8:50
  • Although they seem equivalent they are not Commented Jun 21, 2018 at 8:50
  • 1
    It's actually the equivalent of initialising a private field, so you must use a non-static initialiser. Commented Jun 21, 2018 at 8:53

2 Answers 2

0

In your second example the field is set on first use.

The problem here, is the field intializer is set immediately before the constructor, and there is no guarantee the other property is set or constructed or what order this happens.

If you want to assign something on construction you will need to do it in the constructor

Fields (C# Programming Guide)

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

A field initializer cannot refer to other instance fields.

And some more information

A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members.

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static``readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run tim

Sign up to request clarification or add additional context in comments.

Comments

0

It's, actually, like this:

private readonly MyType _myVariable = new MyType(OtherProperty);
public MyType MyProperty { get { return _myVariable; } }

Thus, the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.