Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initializers and Constructors

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"};
   }
}
like image 653
TampaRich Avatar asked Mar 20 '26 19:03

TampaRich


1 Answers

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) { }
like image 76
Matthew Abbott Avatar answered Mar 23 '26 09:03

Matthew Abbott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!