Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Nbsp;   Initializing Array Elements

In the previous section, I showed how to create an array object and then I showed how to initialize the elements of the array. C# offers syntax that allows you to do these two operations in one statement. The following shows an example.

 

String[] names = new String[] { "Aidan", "Grant" };

 

The comma-separated set of tokens contained within the braces is called an array initializer. Each token can be an arbitrarily complex expression or, in the case of a multi-dimensional array, a nested array initializer. In the preceding example, I used just two simple String expressions.

If you are declaring a local variable in a method to refer to the initialized array, then you can use C#’s implicitly typed local variable (var) feature to simplify the code a little.

 

// Using C#’s implicitly typed local variable feature: var names = new String[] { "Aidan", "Grant" };

 

Here, the compiler is inferring that the names local variable should be of the String[] type because that is the type of the expression on the right of the assignment operator (=).

You can use C#’s implicitly typed array feature to have the compiler infer the type of the array’s

elements. Notice the following line has no type specified between new and [].

 

// Using C#’s implicitly typed local variable and implicitly typed array features: var names = new[] { "Aidan", "Grant", null };

 

In the preceding line, the compiler examines the types of the expressions being used inside the array to initialize the array’s elements, and the compiler chooses the closest base class that all the elements have in common to determine the type of the array. In this example, the compiler sees two Strings and null. Because null is implicitly castable to any reference type (including String), the compiler infers that it should be creating and initializing an array of String references.

If you had this code:

 

// Using C#’s implicitly typed local variable & implicitly typed array features: (error) var names = new[] { "Aidan", "Grant", 123 };

 

the compiler would issue the message error CS0826: No best type found for implicitly­ typed array. This is because the base type in common between the two Strings and the Int32 is Object, which would mean that the compiler would have to create an array of Object references and then box the 123 and have the last array element refer to a boxed Int32 with a value of 123. The C# compiler team thinks that boxing array elements is too heavy-handed for the compiler to do for you implicitly, and that is why the compiler issues the error.

As an added syntactical bonus when initializing an array, you can write the following.

 

String[] names = { "Aidan", "Grant" };


Notice that on the right of the assignment operator (=), only the array initializer expression is given with no new, no type, and no []s. This syntax is nice, but unfortunately, the C# compiler does not al- low you to use implicitly typed local variables with this syntax.



 

// This is a local variable now (error) var names = { "Aidan", "Grant" };

If you try to compile the preceding line of code, the compiler issues two messages: error CS0820: Cannot initialize an implicitly­typed local variable with an array initializer and error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. Although the compiler could make this work, the C# team thought that the compiler would be doing too much for you here. It would be inferring the type of the array, new’ing the array, initializing the array, and inferring the type of the local vari- able, too.

 

The last thing I’d like to show you is how to use implicitly typed arrays with anonymous types and implicitly typed local variables. Anonymous types and how type identity applies to them are dis- cussed in Chapter 10, “Properties.” Examine the following code.

 

// Using C#’s implicitly typed local, implicitly typed array, and anonymous type features: var kids = new[] {new { Name="Aidan" }, new { Name="Grant" }};

 

// Sample usage (with another implicitly typed local variable): foreach (var kid in kids)

Console.WriteLine(kid.Name);

 

In this example, I am using an array initializer that has two expressions for the array elements. Each expression represents an anonymous type (because no type name is specified after the new operator). Because the two anonymous types have the identical structure (one field called Name of type String), the compiler knows that these two objects are of the exact same type. Now, I use C#’s implicitly typed array feature (no type specified between the new and the []s) so that the compiler will infer the type of the array itself, construct this array object, and initialize its references to the two instances of the one anonymous type.1Finally, a reference to this array object is assigned to the kids local variable, the type of which is inferred by the compiler due to C#’s implicitly typed local variable feature.

I show the foreach loop as an example of how to use this array that was just created and initial- ized with the two anonymous type objects. I have to use an implicitly typed local variable (kid) for the loop, too. When I run this code, I get the following output.

 

Aidan Grant

 

 

 
 

1 If you think these sentences are fun to read, you can only imagine how fun they were to write in the first place!



Date: 2016-03-03; view: 763


<== previous page | next page ==>
Nbsp;   Adding Methods to Enumerated Types | Nbsp;   Casting Arrays
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)