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:
var person = new Person() { Name = "Matt" };
The compiler will change this to:
Person person = new Person();
person.Name = "Matt";
(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?
public TestClass(string firstName) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With