ASP.NET Basics (Part 5): Cooking Up a Storm - What's for Dessert?
(Page 4 of 8 )
Thus far, the variables you've used contain only a single value - for example,
<%
int i = 0
%>
However, array variables are a different kettle of fish altogether. An array is a complex variable that allows you to store multiple values in a single variable; it comes in handy when you need to store and represent related information. An array variable can, thus, best be thought of as a "container" variable, which can contain one or more values. For example,
<%
string [] desserts = {"chocolate mousse", "tiramisu", "apple pie", "chocolate fudge cake", "caramel custard"}; %>
Here, "desserts" is an array variable, which contains the values "chocolate mousse", "tiramisu", "apple pie", "chocolate fudge cake", and "caramel custard". It is thus clear that array variables are particularly useful for grouping related values together - names, dates, phone numbers of ex-girlfriends et al.
The definition shown above is a shorthand method to define an array. The proper syntax to define an array in C# is shown below.
<%
// define the type of array
string [] desserts;
// initialize array
// the number indicates the number of elements the array will hold desserts = new string[5];
// assign values to each element
// of the "desserts" array defined above
desserts[0] = "chocolate mousse";
desserts[1] = "tiramisu";
desserts[2] = "apple pie";
desserts[3] = "chocolate fudge cake";
desserts[4] = "caramel custard";
%>
Defining an array variable in C# is a multi-step process, as compared to languages like PHP and Perl; you need to first declare the variable and its type, and then actually create the array.
The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element
chocolate mousse
…you would use the notation…
desserts
[0]
…while…
"chocolate fudge cake"
…would be…
desserts
[3]
- essentially, the array variable name followed by the index number enclosed within square braces. Notice that the first element of the array is referred to by index number 0 instead of 1; geeks refer to this as "zero-based indexing".
Unlike less strict programming languages like PHP and Perl, C# arrays can only store data of the type specified at the time of declaring the array variable - a string array cannot hold numbers, or vice-versa. So, if you were to try the following,
<%
string [] desserts = new string[5];
// assign an integer value
desserts[0] = 100;
%>
C# would fail with an ugly type conversion error message.
Next: Changing Things Around >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire