Reputation: 85
I have a class Product
public class Product
{
public string Name { get; set; }
}
Could you please help me to explain the difference between two case of creating the instance of Product class below?
var instanceOne = new Product
{
Name = "iPhone 4"
}
and
var instanceTwo = new Product()
{
Name = "iPhone 5"
}
Thanks
Upvotes: 0
Views: 126
Reputation:
The ()
is redundant in the following example:
var instanceTwo = new Product()
{
Name = "iPhone 5"
}
You can just write:
var instanceTwo = new Product // <----- () deleted
{
Name = "iPhone 5"
}
Upvotes: 0
Reputation: 35085
There is no difference between these two.
Please note that object initalisers allow specifying constructor parameters too.
class Cat
{
public Cat() {}
public Cat(string name) { Name = name; }
public string Name { get; set; }
public string Color { get; set; }
}
(...)
var lightning = new Cat(Name: "Lightning")
{
Color = "White"
};
var storm = new Cat
{
Name = "Storm",
Color = "Gray"
};
Please also note that
var storm = new Cat
{
Name = "Storm",
Color = "Gray"
};
is not the same as
var storm = new Cat();
storm.Name = "Storm";
storm.Color = "Gray";
The former results in:
var __a = new Cat();
__a.Name = "Storm";
__a.Color = "Gray";
var storm = __a;
as shown in Overview of C# 3.0.
Upvotes: -1
Reputation: 67439
There is no difference, they're the same (assuming you meant to initialize the Name
property, not define it, and it can't be static), except for one very specific case:
Product instanceOne = new()
{
Name = "arf"
};
If you use type-targetted new
, you have to use the new() {...}
version, because new {...}
defines an anonymous type instead.
Upvotes: 2