Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a new instance of class with or without parentheses

Tags:

c#

I'm writing a small example to practice creating new instances of a class.

I have the following code:

class Person
{
   public string Name { get; set; }
   public int Age { get; set; }
}

class MainClass
{
   static void Main()
   {
      var p = new Person
      {
         Name = "Harry",
         Age = 20
      };
      Console.WriteLine($"Name: {p.Name}. Age: {p.Age}");

      p = new Person()
      {
         Name = "Hermonie",
         Age = 18
      };
      Console.WriteLine($"Name: {p.Name}. Age: {p.Age}");

      Console.ReadLine();
   }
}

It's working.

My question: What's the difference between

var p = new Person {};

and

var p = new Person() {};

Which version should I use?

like image 782
Tân Avatar asked Jan 11 '16 10:01

Tân


2 Answers

Both will call the default parameter-less constructor. So I believe both are same.

like image 168
Anup Sharma Avatar answered Oct 13 '22 14:10

Anup Sharma


Unless you wanted to initialize the property values, using the standard:

Person p = new Person();

Should suffice, but they are the same thing in your case and call the default constructor.

But, if you wanted to set the property values, you can do the following:

Person p = new Person { Name = "Harry", Age = 18 };
like image 36
Ric Avatar answered Oct 13 '22 13:10

Ric