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 {}
}
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 {}
}
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.
item()
calls default constructor, whereas item {}
calls default constructor and allows to use (empty in this case) object initializer.
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.