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]" };
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.
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 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