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?
Both will call the default parameter-less constructor. So I believe both are same.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With