Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 2 – Using Collection Initializers

With C# 3.0, any object that implements System.Collections.Generic.IEnumerable<T> and has a public Add method can have its values initialized with a collection initializer.

Using the Point class, let’s create a shape that is made up of a collection of points.

List<Point> Square = new List<Point>

{

new Point { X=0, Y=5 },

new Point { X=5, Y=5 },

new Point { X=5, Y=0 },

new Point { X=0, Y=0 }

};

 

1. For the remainder of the lab a collection of Customers will be needed. Create a list of Customers in a new method CreateCustomers.

 

static void Main(string[] args)

{

Customer c = new Customer(1) { Name = "Maria Anders", City = "Berlin" };

Console.WriteLine(c);

}

 

static List<Customer> CreateCustomers()

{

return new List<Customer>

{

new Customer(1) { Name = "Maria Anders", City = "Berlin" },

new Customer(2) { Name = "Laurence Lebihan", City = "Marseille" },

new Customer(3) { Name = "Elizabeth Brown", City = "London" },

new Customer(4) { Name = "Ann Devon", City = "London" },

new Customer(5) { Name = "Paolo Accorti", City = "Torino" },

new Customer(6) { Name = "Fran Wilson", City = "Portland" },

new Customer(7) { Name = "Simon Crowther", City = "London" },

new Customer(8) { Name = "Liz Nixon", City = "Portland" }

};

}

 

 

2. In Main, replace the code with the following:

static void Main(string[] args)

{

List<Customer> customers = CreateCustomers();

 

Console.WriteLine("Customers:\n");

foreach (Customer c in customers)

Console.WriteLine(c);

}

 

3. Press Ctrl+F5 to build and run the application and print the list of customers. Press any key to terminate the application.

When calling CreateCustomers, the list is initialized empty and each object is created separately. Each object is then added to the list using the Add method.


Date: 2015-02-03; view: 768


<== previous page | next page ==>
Task 3 – Use of Accessibility Modifiers with Properties | Task 1 – Declaring Simple Implicitly Typed Local Variables and Arrays
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)