The purpose of the constructor is to initialize all member variables when an object of this class is created.
How does object initialisation without constructor is assigning values to the property?
Product myProduct = new Product {
ProductID = 100, Name = "Kayak",
Description = "A boat for one person",
Price = 275M, Category = "Watersports"
};
object initialisation with constructor
Product myProduct = new Product(){
ProductID = 100, Name = "Kayak",
Description = "A boat for one person",
Price = 275M, Category = "Watersports"
};
Your two object creation expressions are equivalent. If you don't specify the ()
, it's supplied for you by default.
So:
var foo = new Foo { X = y };
is equivalent to:
var foo = new Foo() { X = y };
From the C# 5 specification, section 7.6.10.1:
An object creation expression can omit the constructor argument list and enclosing parentheses provided it includes an object initializer or collection initializer. Omitting the constructor argument list and enclosing parentheses is equivalent to specifying an empty argument list.
So in both cases you're calling the parameterless constructor of Product
- which is being provided by the compiler because you haven't explicitly declared any constructors. Again from the C# 5 specification, this time section 10.11.4:
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the class is abstract then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public.
(This doesn't include static classes.)
See more on this question at Stackoverflow