https://www.tutorialspoint.com/csharp_online_training/c_object_initializer.asp
using System; namespace ObjectInitializer { class Person { int age; string name; private char gender; static void Main(string[] args) { Person pp1=new Person() { age=10; name="Zaki"; gender='m'; }; } } }
Best:
From the best video and little bit mosh I have written the code below:
without object initializer:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WithoutObjectInitializer { public class Employee { public int id; public string name; public string Department; } class Program { static void Main(string[] args) { Employee emp=new Employee(); emp.id = 1; emp.name = "c#"; emp.Department = "Proramming"; Console.WriteLine(emp.id); Console.WriteLine(emp.name); Console.WriteLine(emp.Department); Console.ReadKey(); } } }
with object initializer:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WithoutObjectInitializer { class Employees { public int id; public string name; public string department; } class WithObjectInit { static void Main(string[] args) { Employees emp=new Employees() { id=1, name="c#", department="programming" }; Console.WriteLine(emp.id); Console.WriteLine(emp.name); Console.WriteLine(emp.department); Console.ReadKey(); } } }
with object initializer:
using System; namespace ObjectInitializer1 { class Program { public int age { get; set; } public string name { get; set; } public char gender { get; set; } static void Main(string[] args) { Program p1=new Program { age=10, name="Zaki", gender ='m' }; Console.WriteLine(p1.name); Console.WriteLine(p1.age); Console.WriteLine(p1.gender); Console.ReadKey(); } } }