Search code examples
c#classinstance

What is the difference between with and without () symbol in creating an instance of an object in C#?


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


Solution

  • 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.