Task 1 – Using Object Initializers
An object initializer consists of a sequence of member initializers, contained in { } braces and separated by commas. Each member initializer assigns a value to a field or property of the object. For example, recall the Point class from Exercise 1: public class Point { public int X { get; set; } public int Y { get; set; } }
An object of type Point can be initialized using an object initializer like this: Point p = new Point { X = 3, Y = 99 };
This concise initialization syntax is semantically equivalent to invoking the instance constructor and then performing assignments for each of the properties.
1. Replace the code in Main with the following: static void Main(string[] args) { Customer c = new Customer(1) { Name = "Maria Anders", City = "Berlin" }; Console.WriteLine(c); }
2. Press Ctrl+F5 to build and run the application. The customer is printed to the console window. Now press any key to terminate the application.
For this object, the object initializer invokes the object’s constructor, and then initializes the named fields to the specified values. Not all fields of the object need to be specified in the list. If not specified, the fields will have their default value. Also note if invoking the object’s parameterless constructor, the parentheses are optional. For example you could have written Customer c = new Customer() {…} as Customer c = new Customer {…}.
|