3

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 {}

}
2

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain your last point? What would the constructors look like for these two examples?
@Peter: There'd be one constructor without parameters and one constructor with a string parameter. They'd be perfectly normal constructors. The type itself doesn't need to know anything about whether object initializers are being used.
6

item() calls default constructor, whereas item {} calls default constructor and allows to use (empty in this case) object initializer.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.