0

I have the following class:

public class TestClass {
    public string ClassName {
        get;
        set;
    }
}

What's the difference between doing:

var instance = new TestClass();

and doing

var instance = new TestClass { };

I thought you needed to include the () to call the object's constructor. What does that mean?

Edit: Can someone explain which is best? Or if one ignores the constructor, benefits or disadvantages?

Edit2: Sorry if I asked something that was already answered. The difference was somewhat clear to me, but I really didn't understand how I could mix and match () and {}, since sometimes the () are ignored and I wanted to know when I could do so

sgarcia.dev
  • 5,671
  • 14
  • 46
  • 80

3 Answers3

5

The first example instantiates a new instance.

The second example instantiates a new instance via object initialization syntax.

They both end up creating a new instance.

You would use the latter if you needed or wanted to set a public property or field of your class during instantiation:

var instance = new TestClass { ClassName = "TestingInstance" };

as opposed to

var instance = new TestClass();
instance.ClassName = "TestingInstance";

It is essentially "syntactic sugar" that makes your life a bit easier (and for some devs more explicit) when creating new objects and setting a lot of properties.

When using object initialization, the params () are optional but the braces {} and statement-ending semi-colon ; are required

David L
  • 32,885
  • 8
  • 62
  • 93
  • 1
    Its just a convienent way of setting properties on a newly created object without having to type `instance.MyProperty = ...` a dozen times. – Ron Beyer May 20 '15 at 15:52
  • 1
    You can even do nested initialization, for instance `new UdpClient{ Client = { ReceiveTimeout = 1000 } };` – default May 20 '15 at 15:56
2

The second piece of code is shorthand syntax for object initialization.

You would use the second syntax when you want to set properties on the object at the same time, like this:

var x = new SomeObject
{
    Property1 = "What's this?",
    Property2 = 42
};

You can combine as well:

var x = new SomeObject("Some constructor parameter", 17, true)
{
    OtherProperty = 42
};

The code can be loosely translated to this:

var temp = new SomeObject("Some constructor parameter", 17, true);
temp.OtherProperty = 42;
var x = temp;
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
0

The second example, with the {}, allows you to set public properties and fields on the object. For instance:

System.Drawing.Point p = new System.Drawing.Point
{
    X = 3,
    Y = 5
};

There's little reason to use {} over () when there's nothing inside the {}.

adv12
  • 8,443
  • 2
  • 24
  • 48