Another concise coding feature in C# 3.0. Let’s see it using user-defined class and other using one of the .Net Collections. This feature demonstrates a new way to initialize a class or a collection.



a. Initializing a User defined class

Lets pick up the employee class example as defined in my whitepaper Auto-Implemented properties in C# 3.0. As we have the class ready lets initialize the object of employee class.



Traditional Approach



employee emp = new employee();

emp.Name = "John";

emp.Designation = "Senior";

emp.GetSalary();

double Sal = emp.Salary;





New Approach



employee emp = new employee { Name = "John", Designation = "Senior" };

emp.GetSalary();



As in the new approach, line 1, you can initialize the employee members (properties) at the time of instantiation. You don’t need to write extra lines of code as done in the traditional approach.



b. Initializing a List Collection



List employees = new List();

employees.Add(new employee{ Name="John", Designation="Junior"});



OR we can even concise it as this:



List employees = new List

{

new employee{ Name="John", Designation="Junior"}

};



So guys say bye to long codes, the future is going to be easier with these concise coding features.

0 comments