5
public class RegisterViewModel{
  public RegisterViewModel()
  {
      MaxDepartmentLevel = db.Settings.Find(1).MaxDepartmentLevel;
  }

  private ApplicationDbContext db = new ApplicationDbContext();
  public int MaxDepartmentLevel { get; set; }
}

Is this safe? Can it guarantee that db will be initialized before the line

MaxDepartmentLevel = db.Settings.Find(1).MaxDepartmentLevel; run?

In other words, what's the execution order of a class with field initialization and constructor?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
guo
  • 9,674
  • 9
  • 41
  • 79

2 Answers2

3

Short answer: yes, your "db" field will always be initialized before the constructor (given that there is no inheritance).

Long answer: It's (almost) never a good idea to execute a database call in the constructor. The constructor should only "construct" the class, not execute its operation. I'd change your code like this

public class RegisterViewModel{
    private ApplicationDbContext db;

    public RegisterViewModel()
    {
        db = new ApplicationDbContext();
    }

    public int QueryMaxDepartmentLevel => db.Settings.Find(1).MaxDepartmentLevel;

}

It gives you control of when your database query executes :)

1

Any constructor invokes parent constructor and then initializes member variables before executing its code. Therefore the code will work.

The initialization order generally is:

  1. Member variables or other constructor of the same class in case of this() call
  2. Parent constructor (skipped in case of this() call)
  3. The provided custom code

See https://msdn.microsoft.com/en-us/library/aa645606(v=vs.71).aspx

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43