13.07.2015 Views

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: C# and <strong>ASP</strong>.<strong>NET</strong> <strong>3.5</strong> 79Creating ArraysYou can use different methods to instantiate an array. Likewise, assigning values to arrayscan be done in different ways. Probably the best way to think about setting up an array isto imagine a stack of safe-deposit boxes. Each box is considered an array element, and thestack itself is the array. Furthermore, you need to specify the number of boxes you needand the type of contents each box will hold. For instance, one stack of boxes can hold onlyjewels and another stack, only money. However, the stack with the jewels cannot holdmoney and vice versa. With that in mind, let’s look at how an array can be instantiated.The general form for declaring an array is as follows:type[] arrayLabel;For instance, the following creates a string array named stringSlots:string[] stringSlots;Unlike a variable, arrays need some kind of indication of how many elements will reside,so when they are instantiated, you need to indicate how big they will be. The followingcreates an array with 44 elements available for data:stringSlots = new string[44];When no values are assigned to a string array, each has a value of null. Integer arraysdefault to 0. However, you can assign values to array elements on initialization. Forexample, the following two examples assign three element values to a string array:string[] stringSlots = new string[3] { "apples" , "oranges" , "pears" };string[] stringSlots = { "apples" , "oranges" , "pears" };The first initialization requires an extra step, so most developers use the second. The arraylength is implied by the three element values that are in curly braces ({}).If you do not know what the values are going to be, you can assign values by a directreference to an array index after the array has been initialized. For example, the followingsequence shows a string array that is declared, initialized, and has data added to specificelements:string[] stringSlots; //declaredstringSlots = new string[44]; //initializedstringSlots[28] = "Nancy"; //value added to element 28stringSlots[43] = "Joe"; //value added to element 43

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!