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

}
amesh
  • 1,311
  • 3
  • 21
  • 51
  • See: [What's the difference between an object initializer and a constructor?](http://stackoverflow.com/questions/740658/whats-the-difference-between-an-object-initializer-and-a-constructor?rq=1) – YetAnotherUser Jul 20 '12 at 16:07
  • I got it already but now I know from Jon skeet that Object{} calling parameter less constructor implicitly. – amesh Jul 20 '12 at 16:14

3 Answers3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Could you please explain your last point? What would the constructors look like for these two examples? – Peter Jul 20 '12 at 16:09
  • 3
    @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. – Jon Skeet Jul 20 '12 at 16:10
6

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

Zbigniew
  • 27,184
  • 6
  • 59
  • 66
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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122