Object and Collection Initializers

Published Wednesday, December 26, 2007 5:03 AM

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<Employee> {
   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

 

Filed under: ,

Comments

# DotNetKicks.com said on Friday, December 28, 2007 5:42 PM

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

# Hernan Garcia said on Monday, December 31, 2007 8:13 PM

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.

# amir.magdy said on Tuesday, January 01, 2008 2:42 AM

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

all syntax enhancements ome in 3.5

Leave a Comment

(required) 
(required) 
(optional)
(required)