I am trying to use Object initializers to set the properties of a class and then access them within the constructor of the class. The problem is that the properties do not seem to be set until after the constructor runs. Am I doing something wrong.
Basic Class..
public class TestClass
{
public string FirstName{get; set;}
public TestClass(){
NewClass nc = NewClass(FirstName);
}
}
Client Class
public class ClientClass
{
public ClientClass(){
TestClass tc = new TestClass{ FirstName="Jimmy"};
}
}
Object initialisers are really syntactic-sugar. Given:
The compiler will change this to:
(well, actually its IL variant)
The constructor will always be executed before any property sets. It’s quite important when creating a constructor that you pass in any parameters are required to correctly initialise your type. In your example, you require FirstName, so why not pass that in as a constructor parameter?