Web
Analytics
Object and Collection Initilizers in C# 3.0 | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

New way of Object Initialization:

          C# 3.0 introduces new way to initialize the objects. Object initialization is used to assign values to accessible fields of an object at the time of creation of Object without invoke the constructor.

Old Approrach

public class Employee

{

public Employee()

{

//

// TODO: Add constructor logic here

//

}

public int empid;

public string name;

public string salary;

}

Initilization of Object and Collection :

Employee em = new Employee();

em.name = "Yogesh Sharma";

em.empid = 1;

em.salary = "2300";



Employee em1 = new Employee();

em1.name = "Vikas Sharma";

em1.empid = 2;

em1.salary = "2400";



Employee em2 = new Employee();

em2.name = "Harsh Sharma";

em2.empid = 3;

em2.salary = "2500";



List emp = new List();

emp.Add(em);

emp.Add(em1);

emp.Add(em2);

Read Values:

foreach(Employee obj in emp)

{

Label1.Text += obj.name+ "
";

} 

C# 3.0 Approach:

List emp = new List {new Employee { empid = 1, name = "ABC", salary = "4000" }, new Employee { empid = 2, name = "XYZ", salary = "1000" }};

Read Values:

foreach(Employee obj in emp)

{

Label1.Text += obj.name+ "
";

}

C# Read Complex Classes:

public class Employee

{

public Employee()

{

//

// TODO: Add constructor logic here

//

}

public int empid;

public string name;

public string salary;

public EmployeeDetail Details;

}

public class EmployeeDetail

{

public string streetaddress;

public string fathername;

}

Traditional Approach:

Employee em = new Employee();

em.Details = new EmployeeDetail();

em.Details.fathername = "AK";

em.Details.streetaddress = "Pratap Nagar";

Employee em1 = new Employee();

em1.Details = new EmployeeDetail();

em1.Details.fathername = "AKsd";

em1.Details.streetaddress = "sd Nagar";

C# 3.0 Apporach:

List emp = new List { new Employee { empid = 1, name = "Yogesh", salary = "1200", Details = new EmployeeDetail { fathername = "AK", streetaddress = "Pratap Nagar" } } };

Read List Values

foreach(Employee obj in emp)

{

Label1.Text += obj.Details.fathername+ "
";

}

DownLoad Source Code of ObjectCollectionInitializer

http://youtu.be/fSV-W6g03EA