CS0236: Field initializer cannot refer to field xyz

  • Thread starter Thread starter cody
  • Start date Start date
C

cody

class Test
{
IList list = new ArrayList();
MyCollection list2 = new MyCollection (list);
}

Leads to this error. I know I could initialize them in the ctor but I'm
asking myself where this restriction come from. Aren't the initializers
called in a well defined order or what is the problem here?
 
C# specification, section 10.4.5.2:

"
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, as it is a compile-time error for a variable
initializer to reference any instance member through a simple-name.
"

Your code MyCollection list2 = new MyCollection (list); would be compiled as
MyCollection this.list2 = new MyCollection (this.list); and it is not
allowed to use this. in the field initialization.
(in a way, there is not yet a this because it is being constructed).
 
Laura said:
C# specification, section 10.4.5.2:

"
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, as it is a compile-time error for a variable
initializer to reference any instance member through a simple-name.
"

Your code MyCollection list2 = new MyCollection (list); would be compiled as
MyCollection this.list2 = new MyCollection (this.list); and it is not
allowed to use this. in the field initialization.
(in a way, there is not yet a this because it is being constructed).

Well, this sounds logical at the first glimpse. I would also disallow
calling of instance methods or properties here because you never know
what these methods do internally.
But for bare naked fields the compiler could make an exception (no pun
intended)?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top