C# object initializers - Include the constructor call parentheses?

Viewed 403

I am a new C# developer.

I have a Class Employee

IS there a difference when declaring an object with and without "()". Visual Studio does not flag an error . For example

Employee newEmployee = new Employee() { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };

or

Employee newEmployee = new Employee { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };
4 Answers

There's no difference in the code samples you've got there. The parentheses are totally optional.

Differences would arise in a couple of variations, though:

First, if your Employee class had a non-default constructor that you want to provide parameters to, you can't omit the parentheses while still passing arguments to the constructor.

Employee newEmployee = new Employee(employeeId) { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };

Second: the next version of C# (9), where type targeting has been improved, so you won't need to include the name of the class if you already declared what type you're creating:

Employee newEmployee = new() { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };

Omitting the parentheses in that case would make the compiler think you're trying to create an anonymous type.

The parentheses and stuff inside the "()" is called a constructor. It's fine to instantiate the object with out the parentheses if your class does not require any parameters. Take a look at this it provides multiple examples of how to instantiate an object with and without parentheses.

Hope you're enjoying C#

If you are not passing any parameters to the constructor, then you can skip opening and closing brackets.

You can read more about it here.

Cat cat = new Cat { Age = 10, Name = "Fluffy" };
Cat sameCat = new Cat("Fluffy"){ Age = 10 };

Class Cat has overloaded constructor so you can pass Name as a parameter.

These are the object initializers anonymously. There are two scenarios:

  • When have to pass something in constructor then must have to use () brackets.
Employee newEmployee = new Employee("David") { LastName = "HasselHoff", Email_ID ="dh@fdh.com" };
  • When not have to pass something in constructor then its optional to use () brackets or not.
Employee newEmployee = new Employee { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };
Employee newEmployee = new Employee() { FirstName = "David", LastName = "HasselHoff", Email_ID ="dh@fdh.com" };

These both are same.

Related