JamesH
JamesH

Reputation: 13

A field initializer cannot reference the nonstatic field: Creating object from { get; set; } result

I am trying to understand a concept and I'm not sure how to go about it. I would really appreciate some help.

What I am trying to do is pull data from a comma separated text file and then use what I pulled to create another object. For example, I want to determine the weeklyWage for a 40 hour week using the hourly wage. If I pulled in the hourly wage from the text file with a { get; set; } is there a way to then say "weeklyWage = hourlyWage * 40"?

public class employee 
{
     public double hourlyWage { get; set; }  
     public double weeklyWage = hourlyWage * 40;
}

error: field initializer cannot reference the non-static field

Upvotes: 0

Views: 58

Answers (1)

Dmytro
Dmytro

Reputation: 1600

The issue you have here is related to the fact that compiler is not aware what is the value of hourlyWage property at the moment field weeklyWage is inializing; so it gives you an error. It (value for weeklyWage) is suppossed to be set from your code, while parsing text file or dynamically calculated. So 2 easy options you to have:

  1. You might use setters of hourlyWage:

    public class employee    
    {
       // This is "backing field" for hourly wage
       private double _hourlyWage;
       // And this is actual property, where business logic happens
       public double hourlyWage
       {
           get
           {
               return _hourlyWage;
           }
           set
           {
               // Set both _hourlyWage and weeklyWage at once
               _hourlyWage = value;
               weeklyWage = _hourlyWage * 40;
           }
       }
       // Public for get, private for set (r
       public double weeklyWage { get; private set; }
    }
    
  2. Or you might want to use dynamic getter:

    public class employee
    {                
            public double hourlyWage{get;set;}    
            public double weeklyWage { get { return hourlyWage * 40; } }
            // "modern" getter syntax would look this way:
            // public double weeklyWage => hourlyWage * 40;
            // Still used "old" syntax for being more expressive.
            // The choice is yours.
    }
    

I would prefer first approach, as value for weeklyWage is calculated once, at the moment hourlyWage is set.

Upvotes: 1

Related Questions