Xeno
Xeno

Reputation: 47

In C#, is there a difference between setting properties using a class constructor and setting the property members directly?

In C#, is there a benefit or different result yielded when you set properties of a object using the class constructor vs creating an object and setting the values of the properties directly? I am new to C# so correct me if I am using terminology incorrectly.

This is the class:

public class Employee
    {
        public int Age;
        public string FirstName;
        public string LastName;
        
        public Employee(string firstName, string lastName, int age)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
        }
    }

When instantiating the object I know I can pass arguments to the constructor. Using:

Employee myEmployee = new Employee("MyName", "MySurname", 30);

If I comment out the class constructor I can still set the properties. Is there a difference doing it this way over the other?

Employee myEmployee = new Employee(){
                FirstName = "MyName",
                LastName = "Surname",
                Age = 32 
            };

All trainings I have taken only shows using the constructor. I am not sure if certain situations would call for using one method over the other or if one actually performs differently.

Upvotes: 2

Views: 1073

Answers (1)

Andrew Richesson
Andrew Richesson

Reputation: 438

No, there is no difference programmatically, but there are semantic differences.

The benefit of using the field initialization is that you can pick and choose what fields to set and leave others null. For example:

var employee = new Employee 
{
   FirstName = "Bob"
};

LastName is now null and Age is now 0. Leaving fields uninitialized like this may cause issues when it's time to use the employee object.

In this situation, it's best to mark all of the fields as Nullable properties by placing a question mark at the end of the type. For example:

public int? Age { get; set; }

This will tell the compiler that these fields could be null since you may have not initialized them. You will get warnings if you try to directly dereference them without checking if they are null first.

But if you want to ensure that every Employee has a FirstName, LastName, and Age, you should use a constructor the requires those fields.

Upvotes: 3

Related Questions