0

Just wanted to know if there is any difference between the two object initialization??

Which one should I be using??

with and without parenthesis ()

var data = new Apple()
{
 Color = "red", 
 Taste = "good"
}

AND

var data = new Apple
{
Color = "red", 
Taste = "good"
}
Aurelia
  • 1,052
  • 6
  • 28
fireholster
  • 622
  • 1
  • 9
  • 22

3 Answers3

7

When you use the second form, in fact it's compiled as the first form. The second form means you want to use the parameterless constructor. Be careful with that because if your class doesn't have any parameterless constructor you can't use it, of course the first form can't also be used.

King King
  • 61,710
  • 16
  • 105
  • 130
1

There is no difference at all. They both will call parameterless constructor.

They are both transformed into:

var data = new Apple();
data.Color = "red";
data.Taste = "good";

by compiler.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

Parameterless constructors are used to save you from the default errors, for example suppose if you have parameterized constructor:

public Apple(string color, string taste)
{
data.Color = "red";
data.Taste = "good";
}

sometime you/user may forget to pass the parameter for constructor Apple(x,y). So it is always a good practice to define a parameterless constructor inside the class like:

public Apple()
{
data.Color = "yellow";
data.Taste = "sour";
}

if you forgot to call the constructor with desired parameters value than the default parameterless constructor will be called and the variables will be initialized to default.

par181
  • 401
  • 1
  • 11
  • 29
  • If your class has reasonable defaults it's a good practice to provide a parameterless constructor. But that's a long way from it *always* being a good practice. There are many cases where you shouldn't have a parameterless constructor, so I'd be wary about recommending it as "always good". – Kyle Nov 18 '13 at 20:40