Search code examples
c#initializer

Using () or {} when instantiating class in C#


Is there any difference in the initialization for x1 and x2?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var x1 = new C { };

            var x2 = new C ();

        }
    }

    public class C
    {
        public int A; 
    }
}

Solution

  • The curly bracket {} is used for object or collection initialization:

    new C() { Property1 = "Value", Property2 = "etc..." };
    

    It should be noted that here the () can be omitted, as it is the default constructor. Therefore, new C{} is basically new C() {}.