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 {}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This syntax:
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:
This syntax:
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:
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.