Reputation: 1329
C# will allow to create an object using either Object() or Object{}. What is the difference with Object() and Object{}
public item getitem()
{
return new item()
}
public item getitem()
{
return new item {}
}
Upvotes: 3
Views: 577
Reputation: 56586
new item {}
uses an object initializer. In your example, there is no difference, but normally you would just call new item()
if you don't wish to actually utilize the object initializer.
Upvotes: 1
Reputation: 1504162
This syntax:
new SomeType{}
is an object initializer expression which happens to set no properties. It calls the parameterless constructor implicitly. You can add property assignments within the braces:
new SomeType { Name = "Jon" }
This syntax:
new SomeType()
is just a call to the parameterless constructor, with no opportunities to set properties.
Note that you can explicitly call a constructor (paramterized or not) with an object initializer too:
// Explicit parameterless constructor call
new SomeType() { Name = "Jon" }
// Call to constructor with parameters
new SomeType("Jon") { Age = 36 }
See section 7.6.10.2 of the C# 4 specification for more details about object initializers.
I would highly recommend that if you aren't setting any properties, you just use new SomeType()
for clarity. It's odd to use an object initializer without setting any properties.
Upvotes: 8
Reputation: 27614
item()
calls default constructor, whereas item {}
calls default constructor and allows to use (empty in this case) object initializer.
Upvotes: 6