'Constructor and field initialization execution order [duplicate]
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?
Solution 1:[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:
- Member variables or other constructor of the same class in case of
this()call - Parent constructor (skipped in case of
this()call) - The provided custom code
See https://msdn.microsoft.com/en-us/library/aa645606(v=vs.71).aspx
Solution 2:[2]
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 :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
