object and collection initializers

Wednesday, December 26, 2007 7:03 AM | Leave a reply »

well also one of the nicest features in c# 3.0 is the object initializers

well we used to do this

   1: Employee emp = new Employee();
   2: emp.FirstName="Amir";
   3: emp.LastName="Magdy";
   4: emp.Title = "Mr.";

i actually hated writing this previous snippet

now in c# 3.0 we do this

   1: var emp = new Employee {FirstName="Amir",LastName="Magdy",Title="Mr."};

u c that's just one line

it's really nicer now that u don't have to write the type name twice as in line 1 first snippet u just type var

also it's way nicer when u do the same for a collection you can initialize a whole collection in one line :D

   1: var Employees = new List {
   2: {new Employee{FirstName="Amir",LastName="Magdy",Title="Mr."}
   3: ,{new Employee{FirstName="John",LastName="Samir",Title="Mr."}
   4: ,{new Employee{FirstName="Mona",LastName="Maurice",Title="Mrs."}
   5: };
i like the syntax it's way shorter and way readable than how it used to

Comments

  1. Gravatar Anonymous says:

    Re : # 

    You've been kicked (a good thing) - Trackback from DotNetKicks.com


  2. Gravatar Anonymous says:

    Re : # 

    C# 3.0 and 3.5 is looking more and more like some dynamic languages like JavaScript (what I like) with the advantages of an strongly typed one.


  3. Gravatar amir.magdy says:

    Re : # 

    actually c# 3.0 only contains the extension wf,wpf,wcf with no syntax enhancements


    all syntax enhancements ome in 3.5


Leave a Reply



 

Please add 3 and 7 and type the answer here: