Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object initializers - Include the constructor call parentheses? [duplicate]

Tags:

c#

object

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 ="[email protected]" };

or

Employee newEmployee = new Employee { FirstName = "David", LastName = "HasselHoff", Email_ID ="[email protected]" };
like image 312
Dylan Devotta Avatar asked Sep 19 '25 17:09

Dylan Devotta


2 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 ="[email protected]" };

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 ="[email protected]" };

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

like image 103
StriplingWarrior Avatar answered Sep 21 '25 06:09

StriplingWarrior


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#

like image 39
Neil L. Avatar answered Sep 21 '25 07:09

Neil L.