I just noticed that using {}
instead of ()
gives the same results when constructing an object.
class Customer
{
public string name;
public string ID {get; set;}
}
static void Main()
{
Customer c1= new Customer{}; //Is this a constructor?
Customer c2= new Customer();
//what is the concept behind the ability to assign values for properties
//and fields inside the {} and is not allowable to do it inside ()
//without defining a constructor:
Customer c3= new Customer{name= "John", ID="ABC"};
}
Does {}
act like ()
when creating a new object in C#?
There are three ways of directly creating a new object in C#:
A simple constructor call with an argument list:
new Foo() // Empty argument list
new Foo(10, 20) // Passing arguments
An object initializer with an argument list
new Foo() { Name = "x" } // Empty argument list
new Foo(10, 20) { Name = "x" } // Two arguments
An object initializer with no argument list
new Foo { Name = "x" }
The last form is exactly equivalent to specifying an empty argument list. Usually it will call a parameterless constructor, but it could call a constructor where all the parameters have default values.
Now in both the object initializer examples I've given, I've set a Name
property - and you could set other properties/fields, or even set no properties and fields. So all three of these are equivalent, effectively passing no constructor arguments and specifying no properties/fields to set:
new Foo()
new Foo() {}
new Foo {}
Of these, the first is the most conventional.
See more on this question at Stackoverflow