#1, 023 – Fields Are Initialized Before Execution of Constructors
January 31, 2014 1 Comment
When you declare a field in a class and initialize the field when it is declared, the initialization of the field will happen when an instance of the class is created, but before the constructor is invoked. All fields are initialized before the constructor executes, in the order in which they are declared.
Assume that we have a Dog class defined as follows:
public class Dog { public string Sound = "Woof"; public Cat Friend = new Cat("Garfield"); public string Name { get; set; } public Dog(string name) { Console.WriteLine("Dog constructor for {0}, Sound is {1}", name, Sound); Name = name; } }
When we create an instance of a Dog, the Sound and Friend fields are initialized before the Dog constructor is invoked.
Dog d = new Dog("Kirby");