Declaring and Referencing Variables

   

Declaring and Referencing Variables

Variables are similar to constants in that when you reference a variable's name in code, C# substitutes the variable's value in place of the variable name when the code executes. This doesn't happen at compile time, however. Instead, it happens at runtime ”the moment the variable is referenced. This is because variables, unlike constants, may have their values changed at any time.

Declaring Variables

graphics/newterm.gif

The act of defining a variable is called declaring. (Variables with scope other than local are dimensioned in a slightly different way, as discussed in the section on scope.) You've already defined variables in previous hours, so the statement should look familiar to you:

  datatype   variablename = initialvalue;  
graphics/bulb.gif

It's possible to declare multiple variables of the same type on a single line. However, this is often considered bad form because it tends to make the code harder to read.

You don't have to specify an initial value for a variable, although being able to do so in the declaration statement is very cool and useful. For example, to create a new string variable and initialize it with a value, you could use two statements, such as the following:

 string strName; strName = "Chris Bermejo"; 

However, if you know the initial value of the variable at design time, you can include it on the declaration statement, like this:

 string strName = "Chris Bermejo"; 

Note, however, that supplying an initial value doesn't make this a constant; it's still a variable, and the content of the variable can be changed at any time. This method of creating an initial value eliminates a code statement and makes the code a bit easier to read because you don't have to go looking to see where the variable is initialized .

It's important to note that C# is a strongly typed language; therefore, you must always declare the data type of a variable. In addition, C# requires that all variables be initialized before they're used.

graphics/bookpencil.gif

Visual Basic programmers should note that C# will not default numeric variables to 0 or strings to empty strings.

For example, the following statements would result in a compiler error in C#: Type or namespace "single" could not be found .

 single sngMyValue; Debug.WriteLine(sngMyValue + 2); 
graphics/bookpencil.gif

You cannot use a reserved word to name a constant or a variable. For instance, you couldn't use public or private as variable names .

Passing Literal Values to a Variable

The syntax of passing a literal value (a hard-coded value such as 6 or "test") to a variable depends on the data type of the variable.

For strings, you must pass the value in quotes, like this:

 strCollegeName = "Bellevue University"; 

There is one caveat when assigning literal values to strings: C# interprets slashes ( \ ) as being a special type of escape sequence. If you pass a literal string containing one or more slashes to a variable, you'll get an error. What you have to do in such instances is preface the literal with the symbol @ , like this:

 strFilePath = @"c:\Temp"; 

When C# encounters the @ symbol, it knows not to treat slashes in the string as escape sequences.

To pass a literal value to a char variable, use single quotes instead of double quotes, like this:

 chaMyCharacter = 'j'; 

For numeric values, you don't enclose the value in anything:

 IntAnswerToEverything = 42; 

Using Variables in Expressions

Variables can be used anywhere an expression is expected. The arithmetic functions, for example, operate on expressions. You could add two literal numbers and store the result in a variable like the following:

 IntMyVariable = 2 + 5; 

You could replace either or both literal numbers with numeric variables or constants, as shown next :

 IntMyVariable = intFirstValue + 5; IntMyVariable = 2 + intSecondValue; IntMyVariable = intFirstValue + intSecondValue; 

Variables are a fantastic way to store values during code execution, and you'll use variables all the time ”from performing decisions and creating loops to using them only as a temporary place to stick a value. Remember to use a constant when you know the value at design time and the value won't change. When you don't know the value ahead of time or the value may change, use a variable with a data type appropriate to the function of the variable.

graphics/bulb.gif

In C#, variables are created as objects. Feel free to create a variable and explore the members of the variable. You do this by entering the variable name and pressing a period (this will work only after you've entered the statement that defines the variable).

Working with Arrays

An array is a special type of variable ”it's a variable with multiple dimensions. Think of an ordinary variable as a single mail slot. You can retrieve or change the contents of the mail slot by referencing the variable. An array is like having an entire row of mail slots (called elements). You can retrieve and set the contents of any of the individual mail slots at any time by referencing the single array variable. You do this by using an index that points to the appropriate slot.

Declaring Arrays

Before you can use an array, you must first declare it (the same as you have to declare variables). Consider the following statements:

 string[] strMyArray; strMyArray = new string[10]; 

The first statement declares strMyArray as an array, and the second statement defines the array as having 10 string elements.

The number in brackets specifies how many "mail slots" the array variable will contain, and it can be a literal value, a constant, or the value of another variable.

Referencing Array Variables

To place a value in an array index, you specify the index number when referencing the variable. Most computer operations consider 0 to be the first value in a series ”not 1, as you might expect. This is how array indexing behaves. For example, for an array dimensioned with 10 elements, you would reference the elements sequentially using the indexes 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Notice that the upper index is one fewer than the total elements because 0 is the first index, not 1. Therefore, to place a value in the first element of the array variable, you would use 0 as the index, like this:

 strMyArray[0] = "This value goes in the first element"; 

The data type specified for the array variable is used for all the elements in the array. This is where the object data type can come in handy. For example, suppose you wanted to store the following pieces of information in an array: Name, City, State, Age, and DateOfBirth. As you can see, you need to store string values for Name, City, and State, but you need to store a number for Age. By dimensioning an array variable as data type object, you can store all these different types of data in the array; C# will determine the data type of each element as the data is placed into it. The following shows an example of a declaration of such an array:

 object[] objPersonalInfo; objPersonalInfo = new object[10]; 

Again, after it's defined, you can reference the array variable as you would an ordinary variable, with the exception that you must include an index. For example, you could populate the array using code like this:

 objPersonalInfo[0] = "James Foxall"; objPersonalInfo[1] = "Papillion"; objPersonalInfo[2] = "Nebraska"; objPersonalInfo[3] = 32; 

Creating Multidimensional Arrays

Array variables require only one declaration, yet they can store numerous pieces of data; this makes them perfect for storing sets of related information. The array example shown previously is a single-dimension array. Arrays can be much more complex than this example and can have multiple dimensions of data. For example, a single array variable could be defined to store the personal information shown previously for different people. Multidimensional arrays are declared with multiple parameters such as the following:

 int[,] intMeasurements; intMeasurements = new int[3,2]; 

These statements create a two-dimensional array. The first dimension (defined as having three elements) serves as an index to the second dimension (defined as having two elements). Suppose you wanted to store the height and weight of three people in this array. You reference the array as you would a single-dimension array, but you include the extra parameter index. The two indexes together specify an element, much like coordinates in Battleship relate to specific spots on the game board. Figure 12.1 illustrates how the elements are related.

Figure 12.1. Two-dimensional arrays are like a wall of mail slots.

graphics/12fig01.gof


Elements are grouped according to the first index specified; think of the first set of indexes as being a single-dimension array. For example, to store the height and weight of a person in the array's first dimension, you could use code such as the following:

 intMeasurements[0,0] =  FirstPersonsHeight;  intMeasurements[0,1] =  FirstPersonsWeight;  

I find it helpful to create constants for the array elements, which makes array references much easier to understand. Consider the following:

 const int c_Height = 0; const int c_Weight = 1; intMeasurements[0,c_Height] = FirstPersonsHeight; intMeasurements[0,c_Weight] = FirstPersonsWeight; 

You could then store the height and weight of the second and third person like this:

 intMeasurements[1,c_Height] =  SecondPersonsHeight;  intMeasurements[1,c_Weight] =  SecondPersonsWeight;  intMeasurements[2,c_Height] =  ThirdPersonsHeight;  intMeasurements[2,c_Width] =  ThirdPersonsWeight;  

In this array, I've used the first dimension to differentiate people. I've used the second dimension to store a height and weight for each element in the first dimension.

Because I've consistently stored heights in the first slot of the array's second dimension and weights in the second slot of the array's second dimension, it becomes easy to work with these pieces of data. For example, you can retrieve the height and weight of a single person as long as you know the first dimension index used to store the data. You could, for instance, print out the total weight of all three people using the following code:

 Debug.WriteLine(intMeasurements[0,c_Weight] + intMeasurements[1,c_Weight] +                 intMeasurements[2,c_Weight]); 

When working with arrays, keep the following points in mind:

  • The first element in any dimension of an array has an index of 0.

  • Dimension an array to hold only as much data as you intend to put into it.

  • Dimension an array with a data type appropriate to the values to be placed in the array's elements.

Arrays are an extremely powerful and easy way to store and work with related sets of data in C# code. Arrays can make working with larger sets of data much simpler and more efficient than using other methods . To maximize your effectiveness with arrays, study the for loop discussed in Hour 15, "Looping for Efficiency." Using a for loop, you can quickly iterate through all the elements in an array.

graphics/bookpencil.gif

This section discussed the rectangular type of a C# multidimensional array. C# also supports another type of multidimensional array called jagged. Jagged arrays are an array of one-dimensional arrays, each of which can be of different lengths. However, teaching jagged arrays is beyond the scope of this book.


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net