Variables

   

Variables

Your programs need to store values. For instance, you might have a program that calculates the resistance of an electrical circuit based on the amperage and voltage. The user inputs the amperage and voltage, and the resistance is calculated. The amperage and voltage, though, need to be stored somewhere so that when the calculation is performed, the values that the user entered are available.

Variables not only store values, but they can be altered . You can multiply a value that's stored in a variable by 5, increment it, negate it, or any number of other operations.

Variables can control the flow of a program's execution and affect the overall state of a program. They are a fundamental part of programming languages; without them, you'd be hard-pressed to develop software.

Declaring Variables

Before you use a variable, you must declare it. A variable has two parts : the data type and the identifier.

The data type determines the legal range of values that a variable may contain, what operations may be applied to the variable, and how such operations are performed. For instance, an integer variable deals with whole numbers; a double variable deals with floating-point numbers .

The identifier is used to associate a name with a variable. This gets confusing for some of my students. They think the name of a variable is int . It's not. The name is anything you want to give it, such as George, Sam, and Steve. The int part of it has nothing to do with the name. The general structure of variable declaration can be seen below.

 type identifier; 

Any number of variables can be declared on a single line, each the same type, as long as each identifier is unique and separated from the others by a comma. For C# and JScript a semicolon is used to signal the end of a variable declaration. Many programmers who will probably read this book have experience with JavaScript, but JScript.NET is the first JavaScript variant that allows type definitions when declaring variables.

Here, an integer variable is declared and is given the name horizontal :

VB

 Dim horizontal as Integer 

C#

 int horizontal; 

JScript

 var horizontal : int; 

Variable Names and Hungarian Notation

Hungarian notation is a commonly used method of naming variables so that their type is indicated in the variable name. This enables the programmer to look at the variable name and know the type without seeing the actual definition. Using Hungarian notation can help reduce the number of errors when programming. Hungarian notation will be used throughout the book. The following C# examples show how Hungarian notation is used.

Integers can be preceded by an n or i character. In this book, the n character will be used for signed and i for unsigned.

int nValue;

int iValue;

Longs are preceded by an l character.

long lValue;

Doubles are preceded by a d character.

double dValue;

Strings are preceded by the str characters .

String strData;

Member variables are usually preceded with m_ whereas local variables are not, as in the following examples:

Integer member variable.

int m_nValue;

String member variable.

String m_strData;

Integer local variable.

int nValue;

String local variable.

String strData;

Some variables with single character names are left as single characters if it's clear what they're being used for. Examples of this are variables named x , y , and i . A variable named x almost always signifies the x value of a coordinate pair, whereas a variable named y almost always signifies the y value of a coordinate pair. A variable named i is almost always used as a local loop counter.

In the following example, several integer variables are declared, all on the same line:

VB

 Dim nHorizontal, nVertical, x, y, nMonths, nYears, nDays as Integer 

C#

 int nHorizontal, nVertical, x, y, nMonths, nYears, nDays; 

JScript

 var nHorizontal : int, nVertical : int, x : int, y; 

However, you could have broken the above declaration into a number of declarations:

VB

 Dim nHorizontal as Integer  Dim nVertical as Integer  Dim x as Integer  Dim y as Integer  Dim nMonths as Integer  Dim nYears as Integer  Dim nDays as Integer 

C#

 int nHorizontal;  int nVertical;  int x;  int y;  int nMonths;  int nYears;  int nDays; 

JScript

 var nHorizontal : int;  var nVertical : int;  var x : int;  var y : int;  var nMonths : int;  var nYears : int;  var nDays : int; 

How you declare your variables depends mainly on personal taste. Many programmers would choose the first example for the simple format.

Keep in mind that declarations become much more readable with the variables grouped in ways that help people reading the code understand the variable organization. You should also think about indenting to improve readability.

Variable Types

Variables used to fall into two categories: primitives and references to objects. With .NET, all variables are objects. In spite of this, I'm still going to separate them because you still will usually think of them as two types. This section talks about the difference between these two variable types.

Your programs are likely to use a number of different primitive variables. Any variable that you declare of type int, long, float, or double is a primitive variable.

Reference variables are used to store references, or pointers, to objects. (Keep in mind that I'm not referring to pointers such as those used in C and C++ here, but rather to the concept of pointing to an object in memory.) These objects can be class instances, class instances that implement interfaces, or arrays.

The following are examples of reference variable declarations for several types (shown here in C#):

 string strHelloString;  // Class instance.  Bitmap MyBitmap;  // Class instance of a Bitmap, an interface.  int[] nHighScores;  // Array of integers. 

Initializing and Storing Values in Variables

After a variable has been declared, a value may be stored in it. This may be done either at the time a variable is declared ”a process known as initialization (assigning a value to the variable) ”or anytime after is has been declared. In either case, any value assigned to the variable must be of the same type as the variable itself. All variables are initialized at declaration in the .NET architecture. Even if they are not initialized explicitly, as shown in the examples below, they do get initialized to a default value. This is unlike Java, C, and C++, where variables are not initialized unless explicitly programmed to do so.

The following are examples of variables being initialized at the time of declaration:

VB

 Dim nCounter as Integer = 900  Dim dExactBalance as Double = 452.77 

C#

 byte x = 3;  int nCounter = 900;  long lBacterialCount = 12249123;  float fAccountBalance = 152;  double dExactBalance = 452.77;  char cMiddleInitial = 'R'; 

JScript

 var nCounter : int = 900;  var dExactBase : double = 452.77; 

In each of the preceding examples, a value consistent with the variable's data type is assigned to it at the time of declaration. These variables have been initialized. From the moment the variables are created, they contain a value. Notice, however, that there is no example of an array being initialized.

Array Initialization

In the case of arrays, each element may contain a value. If you declare an array that has five integer elements, it can hold five different integers.

When an array is initialized, it's done in two steps. First, you declare the number of elements the array will have. Then each element in the array is individually initialized, or set to a value (usually zero). Here is an example of how you would initialize an array of integers:

VB

 Dim nHighScores(5) as Integer  nHighScores(0) = 15  nHighScores(1) = 25  nHighScores(2) = 37  nHighScores(3) = 4  nHighScores(4) = 19 

C#

 int[] nHighScores = new int[5];  nHighScores[0] = 15;  nHighScores[1] = 25;  nHighScores[2] = 37;  nHighScores[3] = 4;  nHighScores[4] = 19; 

JScript

 var nHighScores : int[] = new int[5];  nHighScores[0] = 15;  nHighScores[1] = 25;  nHighScores[2] = 37;  nHighScores[3] = 4;  nHighScores[4] = 19; 

Variable Scope

Every variable has an associated scope, which is the extent to which it can be used. The scope of a variable begins immediately where it is declared and, in C# and JScript, ends with the closing brace (}) of the block of code within which it is declared; in VB, it ends with an End , Next , While End , or Else . You can access a variable only within its scope. If you attempt to access a variable outside its scope, the compiler generates an error.

In the following examples, I use three local variables in a method: i , j , and k . The variable i is in scope for the entire method. The variable j is in scope inside the for loop. And the variable k is in scope in the if conditional.

VB

 Sub Foo    Dim i as Integer    For i=0 to 12      Dim j as Integer      j = i * 8      If j = 16 Then        Dim k as Integer        k = j + I      End If ' End of scope for k.      ' Trying to access k here will result in a compiler error.    Next ' End of scope for j.    ' Trying to access j here will result in a compiler error.  End Sub ' End of scope for i. 

C#

 public void Foo( void )  {    int i;    for( i=0; i<12; i++ )    {      int j;      j = i * 8;      if( j == 16 )      {        int k;        k = j + i;      }// End of scope for k.      // Trying to access k here will result in a compiler error.    }// End of scope for j.    // Trying to access j here will result in a compiler error.  }// End of scope for i. 

JScript

 public void Foo( void )  {    var i : int;    for( i=0; i<12; i++ )    {      var j : int;      j = i * 8;      if( j == 16 )      {        var k : int;        k = j + i;      }// End of scope for k.      // Trying to access k here will result in a compiler error.    }// End of scope for j.    // Trying to access j here will result in a compiler error.  }// End of scope for i. 

Variables that are declared as member variables of a class have a valid scope throughout the class. For example, the C# Variables class in Listing 2.1 has three member variables: m_nHorizontal , m_nVertical , and m_bButton . These variables can be accessed in any of the class's methods .

Listing 2.1 Declaring Variables in the Variables Class
 namespace LanguageChapter  {      using System;      using System.Collections;      using System.ComponentModel;      using System.Data;      using System.Drawing;      using System.Web;      using System.Web.SessionState;      using System.Web.UI;       using System.Web.UI.WebControls;      using System.Web.UI.HtmlControls;      public class Variables : System.Web.UI.Page      {          int m_nVarOne = 5, m_nVarTwo = 10;          bool m_bVarThree = false;          public Variables ()          {              Page.Init += new System.EventHandler(Page_Init);              m_nVarOne += 5;          }          protected void Page_Load(object sender, EventArgs e)          {              m_nVarTwo += m_nVarOne;              if (!IsPostBack)              {                  m_bVarThree = true;              }          }          protected void Page_Init(object sender, EventArgs e)          {              InitializeComponent();              m_nVarTwo -= m_nVarOne;          }          private void InitializeComponent()          {              this.Load += new System.EventHandler (this.Page_Load);          }      }  } 

Suppose, though, that you declared the horizontal and vertical integers in a method. If this were the case, the scope of these variables would be limited to the method in which they were declared. Any attempt to access these variables outside of your method would generate an error, because the variables can't be accessed outside their scope. Look at the following example in VB:

 Sub DoSomething      Dim nHorizontal as Integer = 100      Dim nVertical as Integer = 50      strInfo = "Vertical: " + CStr( nHorizontal ) + _          "  Horizontal: " + CStr( nVertical ) + "<br>"      Response.Write( strInfo )  End Sub  Sub DoSomethingElse      ' ILLEGAL-attempt to access outside of scope.      nVertical = CInt( Request.Form( "Vertical" ) )      ' ILLEGAL-attempt to access outside of scope.      nHorizontal = CInt( Request.Form( "Horizontal" ) )  End Sub 

A special situation can occur in which a variable is hidden by the declaration of another variable with the same name. This happens if the second variable declaration happens within a sub-block of code residing in the original variables immediately following the class signature, as in Listing 2.1. Clearly, the scope of these variables would be the entire class itself.

However, if you also declared m_nHorizontal and m_nVertical integer variables inside a method, the original variables would be hidden from that method. In this case, any reference to the m_nHorizontal and m_nVertical variables inside the method would refer to the variables declared in that method, rather than the original ones as illustrated in the following JScript example. (Avoiding this kind of mix-up is a major reason why the names of member variables begin with m_ and names of local variables do not.)

 var m_nHorizontal : int, m_nVertical : int;  function DoSomething()  {     var m_nHorizontal : int, m_nVertical : int;     // Local variables of the same name.     var strInfo : String;     strInfo = "Vertical: " + m_nVertical +         "  Horizontal: " + m_nHorizontal + "<br>";     Response.Write( strInfo );     // Uses the local variables declared here in paint(),     // not the class member variables.  }  function DoSomethingElse()  {     // Refers to member variable, not     // the local variable declared in DoSomething().     m_nHorizontal = 17;     // Refers to member variable, not     // the local variable declared in DoSomething().     m_nVertical = 65;  } 
   


Special Edition Using ASP. NET
Special Edition Using ASP.Net
ISBN: 0789725606
EAN: 2147483647
Year: 2002
Pages: 233

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