Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C# field initialization requirements

Considering the following code:

public class Progressor {     private IProgress<int> progress = new Progress<int>(OnProgress);      private void OnProgress(int value)     {         //whatever     } } 

This gives the following error on compilation:

A field initializer cannot reference the non-static field, method, or property 'Progressor.OnProgress(int)'

I understand the restriction it is complaining about, but I don't understand why it is an issue, but the field can be initialized in the constructor instead as follows:

public class Progressor {     private IProgress<int> progress;      public Progressor()     {          progress =  new Progress<int>(OnProgress);     }      private void OnProgress(int value)     {         //whatever     } } 

What is the difference in C# regarding the field initialization vs constructor initialization that requires this restriction?

like image 986
Yishai Avatar asked Dec 15 '14 19:12

Yishai


People also ask

Is C easy to understand?

It is hard to learn because: It has complex syntax to support versatility. It is a permissive language—you can do everything that's technically possible, even if not logically right. It is best learned by someone who already has a foundation with C programming.

Is C good for beginners?

It's not. C is a low-level language that provides few high-level abstractions. It has been described as a “portable assembler.” C is a dangerous language to use for the uninitiated.


2 Answers

Field initialization come before base class constructor call, so it is not a valid object. Any method call with this as argument at this point leads to unverifiable code and throws a VerificationException if unverifiable code is not allowed. For example: in security transparent code.

  • 10.11.2 Instance variable initializers
    When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. The variable initializers are executed in the textual order in which they appear in the class declaration.
  • 10.11.3 Constructor execution
    Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.
like image 91
user4003407 Avatar answered Sep 29 '22 15:09

user4003407


Everything in my answer is just my thoughts on 'why it would be dangerous to allow that kind of access'. I don't know if that's the real reason why it was restricted.

C# spec says, that field initialization happens in the order fields are declared in the class:

10.5.5.2. Instance field initialization

The variable initializers are executed in the textual order in which they appear in the class declaration.

Now, let's say the code you've mentioned is possible - you can call instance method from field initialization. It would make following code possible:

public class Progressor {     private string _first = "something";     private string _second = GetMyString();      private string GetMyString()     {         return "this is really important string";     } } 

So far so good. But let's abuse that power a little bit:

public class Progressor {     private string _first = "something";     private string _second = GetMyString();     private string _third = "hey!";      private string GetMyString()     {         _third = "not hey!";         return "this is really important string";     } } 

So, _second get's initialized before _third. GetMyString runs, _third get's "not hey!" value assigned, but later on it's own field initialization runs, and it's being set to `"hey!". Not really useful nor readable, right?

You could also use _third within GetMyString method:

public class Progressor {     private string _first = "something";     private string _second = GetMyString();     private string _third = "hey!";      private string GetMyString()     {         return _third.Substring(0, 1);     } } 

What would you expect to be value of _second? Well, before field initialization runs all the fields get default values. For string it would be null, so you'll get unexpected NullReferenceException.

So imo, designers decided it's just easier to prevent people from making that kind of mistakes at all.

You could say, OK let's disallow accessing properties and calling methods, but let's allow using fields that were declared above the one you want to access it from. Something like:

public class Progressor {     private string _first = "something";     private string _second = _first.ToUpperInvariant(); } 

but not

public class Progressor {     private string _first = "something";     private string _second = _third.ToUpperInvariant();     private string _third = "another"; } 

That's seems useful and safe. But there is still a way to abuse it!

public class Progressor {     private Lazy<string> _first = new Lazy<string>(GetMyString);     private string _second = _first.Value;      private string GetMyString()     {         // pick one from above examples     } } 

And all the problems with methods happen to come back again.

like image 32
MarcinJuraszek Avatar answered Sep 29 '22 13:09

MarcinJuraszek