Close

c# – Instantiate an object and set it’s Properties simultaneously (using the Initialization approach)

 

Announcement

I have released my new course on Udemy, Kubernetes By Example. Sign up now to get free lifetime access!

1st Approach: Using Initialization

Here we use properties (as demonstrated in the previous), but this time we set all the properties in one go, by writing them as part of the object’s actual declaration, using curly-bracket syntax:

[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Employee
{
public string Firstname {get; set;}
public int Age {get; set;}
public double Salary {get; set;}
}

class Program
{
static void Main()
{
Employee Dave = new Employee()
{
Firstname = "David",
Age = 35,
Salary = 35235.23
};
// Using the above syntax is called initialisation

Console.WriteLine("{0} is {1} years old and earns £{2} per year.", Dave.Firstname, Dave.Age.ToString(), Dave.Salary.ToString());
}
}
[/csharp]