12.1. Object and Array Initialization

With the introduction of the .NET Framework, Microsoft moved developers into the world of object-oriented design. However, as you no doubt will have experienced, there are always multiple class designs with quite often no one right answer. One such open-ended example is the question of whether to design your class to have a single parameterless constructor, multiple constructors with different parameter combinations, or a single constructor with optional parameters. This choice is often dependent on how an instance of the class will be created and populated. In the past this might have been done in a number of statements, as shown in the following snippet:

VB.NET

Dim p As New Person
With p
    .FirstName = "Bob"
    .LastName = "Jane"
    .Age = 34
End With

C#

Person p = new Person();
p.FirstName = "Bob";
p.LastName = "Jane";
p.Age = 34;

If you have to create a number of objects this can rapidly make your code unreadable, which often leads designers to introduce constructors that take parameters. Doing this will pollute your class design with unnecessary and often ambiguous overloads. Now you can reduce the amount of code you have to write by combining object initialization and population into a single statement:

VB.NET

Dim p As New Person With {.Firstname = "Bob", .LastName = "Jane", .Age = 34}

C#

Person p = new Person {FirstName="Bob", LastName="Jane", Age=34};

You can initialize the object with any of the available constructors, as shown in the following VB.NET snippet, which uses a constructor where the parameters are the first and second name of the Person object being created:

Dim p As New Person("Bob", "Jane") With {.Age = 34}

As you can see from this snippet, it is less clear what the constructor parameters represent. Using named elements within the braces makes it easier for someone else to understand what properties are being set. You are not limited to just public properties. In fact, any accessible property or field can be specified within the braces. This is illustrated in Figure 12-1, where the IntelliSense drop-down shows the available properties and fields. In this case Age is a public property and mHeight is a public member variable.

Figure 12.1. Figure 12-1

You will notice that the IntelliSense drop-down contains within the braces only the properties and fields that haven't already been used. This is only a feature of IntelliSense within C#. However, if you try to set a field or property multiple times in either language, you will get a build error.

As you have seen, object initialization is a shortcut for combining the creation and population of new objects. However, the significance of being able to create an object and populate properties in a single statement is that you can incorporate this ability into an expression tree. Expression trees are the foundation of LINQ, allowing the same syntax to be reused to query collections of objects, as well as XML and SQL data. Working directly with expression trees will be covered in more detail at the end of this chapter.

Object initialization can also be useful when you're populating arrays, collections, and lists. In the following snippet, an array of Person objects can be defined in a single statement.

VB.NET

Dim people As Person() = New Person() { _
                     New Person With {.FirstName = "Bob", .LastName = "Jane"}, _
                     New Person With {.FirstName = "Fred", .LastName = "Smith"}, _
                     New Person With {.FirstName = "Sarah", .LastName = "Plane"}, _
                     New Person With {.FirstName = "Jane", .LastName = "West"} _
                                       }

C#

Person[] people = new Person[]{
                              new Person {FirstName = "Bob", LastName = "Jane"},
                              new Person {FirstName = "Fred", LastName = "Smith"},
                              new Person {FirstName = "Sarah", LastName = "Plane"},
                              new Person {FirstName = "Jane", LastName = "West"}
                               };

In both languages you can omit the call to the array constructor (i.e. New Person() or new Person[]), as this is implicitly derived from the array initialization. If you are coding in C# you can apply this same syntax to the initialization of collections and lists, or any custom collection you may be creating.

List<Person> people = new List<Person>{
                             new Person {FirstName = "Bob", LastName = "Jane"},
                             new Person {FirstName = "Fred", LastName = "Smith"},
                             new Person {FirstName = "Sarah", LastName = "Plane"},
                             new Person {FirstName = "Jane", LastName = "West"}
                                       };

In order for your custom collection to be able to use this syntax, it must both implement IEnumerable and have an accessible Add method (case-sensitive). The Add method must accept a single parameter that is the type, or a base class of the type, that you are going to be populating the list with. If there is a return parameter, it is ignored.

VB.NET developers can still use the IEnumerable constructor overload on a number of common collections and lists in order to populate them.

Dim people As New List(Of Person)(New Person() { _
                     New Person With {.FirstName = "Bob", .LastName = "Jane"}, _
                     New Person With {.FirstName = "Fred", .LastName = "Smith"}, _
                     New Person With {.FirstName = "Sarah", .LastName = "Plane"}, _
                     New Person With {.FirstName = "Jane", .LastName = "West"} _
                                                })

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.21.158