May 10, 2014

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



You can find all my latest posts on medium.

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:

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());