Error message

In C#, instance fields cannot be used to initialize other instance fields outside a method. This is the compiler error CS0236

example.cs

using System;
public class Example {
    public Decimal dividend = new Decimal(2);

    // the line below will result in a compiler error
    public Decimal divisor = dividend; // CS0236
}

Cause

Understanding the order of actions performed when initializing a new instance could help us figure out why this is.

We can get the full details for the actions from the C# programming guide ; an outline is provided below:

order of actions for instance initialization

  1. Instance fields are set to 0. This is typically done by the runtime.
  2. Field initializers run. The field initializers in the most derived type run.
  3. Base type field initializers run. Field initializers starting with the direct base through each base type to System.Object.
  4. Base instance constructors run. Any instance constructors, starting with Object.Object through each base class to the direct base class.
  5. The instance constructor runs. The instance constructor for the type runs.
  6. Object initializers run. If the expression includes any object initializers, those run after the instance constructor runs. Object initializers run in the textual order.

It can be observed from the list that field initializers are run before the instance constructor. This means instance fields don’t exist at the moment the instance initializers are executed. The compiler cannot allow any instance property or field to be referenced before the class instance is fully constructed.

In the case of the example provided earlier, the instance created from new Decimal(2) does not exist at the moment dividend is initialized.

A lot more can be learned from this excellent StackOverflow answer

Solution

The recommended solution is to initialize the instance field in the class constructor.