User:Foxall/12

Ka Wiktionary

Hour 12. Using Constants, Data Types, Variables, and Arrays[wax ka badal]

graphics/newterm.gif As you write your C# methods, you'll regularly need to store and retrieve various pieces of information. In fact, I can't think of a single application I've written that didn't need to store and retrieve data in code. For example, you might want to keep track of how many times a method has been called, or you may want to store a property value and use it at a later time. Such data can be stored as constants, variables, or arrays. Constants are named values that you define once at design time but that can be referenced as often as needed. Variables, on the other hand, are like storage bins; you can retrieve or replace the data in a variable as often as you need to. Arrays act like grouped variables, allowing you to store many values in a single array variable.
graphics/newterm.gif Whenever you define one of these storage entities, you must decide the type of data it will contain. For example, is a new variable going to hold a string value (text) or perhaps a number? If it will hold a number, is the number a whole number, an integer, or something else entirely? After you determine the type of data to store, you must choose the level of visibility that the data has to other methods within the project (this visibility is known as scope). In this hour, you'll learn the ins and outs of C# new data types, how to create and use these "storage" mechanisms, and you'll learn how to minimize problems in your code by reducing scope.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec1.htm#ch12lev1sec1 Understanding data types]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec1.htm#ch12lev2sec1 Determining data type]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec1.htm#ch12lev2sec1 Converting data to different data types]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec2.htm#ch12lev1sec2 Defining and using constants]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec3.htm#ch12lev1sec3 Dimensioning and referencing variables]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec3.htm#ch12lev2sec6 Working with arrays]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec4.htm#ch12lev1sec4 Determining scope]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec5.htm#ch12lev1sec5 Using a naming convention]
graphics/bookpencil.gif I cover a lot of important material in this hour, but you'll notice a lack of hands-on examples. You're going to use variables throughout the rest of this book, and you've already used them in earlier hours. I've used the space in this hour to teach you the meat of the subject; you'll get experience with the material in other hours.

>

Understanding Data Types

In any programming language, it's critical that the compiler, the part of the Visual Studio framework that interprets the code you write into a language the computer can understand, fully understands the type of data you're manipulating in code. For example, if you asked the compiler to add the following values, it would get confused:

659 / "Dog"
graphics/newterm.gif When the compiler gets confused, it either refuses to compile the code (which is the preferred situation because you can address the problem before your users run the application), or it will halt execution and display an exception (error) when it reaches the confusing line of code. (These two types of errors are discussed in detail in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch16.htm#ch16 Hour 16], "Debugging Your Code.") Obviously, you can't subtract 659 by the word "Dog"; these two values are different types of data. In C#, these two values are said to have two different data types. In C#, constants, variables, and arrays must always be defined to hold a specific type of information.
Determining Data Type
graphics/newterm.gif Data typing�the act of defining a constant, a variable, or an array's data type�can be confusing. To C#, a number is not a number. A number that contains a decimal value is different from a number that does not. C# can perform arithmetic on numbers of different data types, but you can't store data of one type in a variable with an incompatible type. Because of this limitation, you must give careful consideration to the type of data you plan to store in a constant, a variable, or an array at the time you define it. C# supports two categories of data types: value types and reference types. The main difference between these two types is how their values are stored in memory. As you continue to create more complex applications, this difference may have an impact on your programming. For this book, however, this distinction is minimal. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12table01 Table 12.1] lists the C# data types and the range of values they can contain.
Data Type�Value Value Range
bool true or false
byte 0 to 255
char a single character
decimal �79,228,162,514,264,337,593,543,950,335 to �7.9228162514264337593543950335. Use this data type for currency values
double �1.79769313486232E308 to �4.94065645841247E-324 for negative values; 4.94065645841247E�324 to 1.79769313486232E308 for positive values
float �3.402823E38 to �1.401298E�45 for negative values; 1.401298E�45 to 3.402823E38 for positive values
int �2,147,483,648 to 2,147,483,647.
long �9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
sbyte �128 to 127
short �32,768 to 32,767
uint Integers in the range from 0 to 4,294,967,295
ulong Integers in the range from 0 to 10^20
ushort Integers in the range from 0 to 65,535
Data Type�Reference Value Range
string 0 to approximately 2 billion characters
object Any type can be stored in a variable type Object

C# supports unsigned data types for short, int, and long (the types prefaces with u, such as uint). Because negative numbers are excluded (there is no sign) this has the effect of doubling the positive values for a short, an int, or a long. Signed data types are preferable and should be used unless you have a very good reason for doing otherwise (such as declaring a variable that will never hold a negative value).

Tips for Determining Data Type[wax ka badal]

The list of data types may seem daunting at first, but you can follow some general guidelines for choosing among them. As you become more familiar with the different types, you'll be able to fine-tune your data type selection.

Following are some helpful guidelines for using data types:

  • If you want to store text, use the string data type. The string data type can be used to store any valid keyboard character, including numbers and nonalphabetic characters.
  • If you want to store only the values true or false, use the bool data type.
  • If you want to store a number that contains no decimal places and is greater than �32,768 and smaller than 32,767, use the short data type.
  • If you need to store numbers with no decimal places but with values larger or smaller than short allows, use the int or long data types.
  • If you need to store numbers that contain decimal places, use the float data type. The float data type should work for almost all your values containing decimals, unless you're writing incredibly complex mathematical applications or need to store very large numbers; in that case, use a double.
  • If you need to store currency amounts, use the decimal data type.
  • If you need to store a single character, use the char data type.
Casting Data from One Data Type to Another
graphics/newterm.gif Under some circumstances, C# won't allow you to move data of one type into a variable of another type. The process of changing a value's data type is known as casting. C# supports two types of casting: implicit and explicit. Implicit conversions are done automatically by the compiler. These conversions guarantee that no data is lost in the conversion. For instance, you can set the value of a variable declared as double to the value of a variable declared as float without an explicit cast because there is no risk of losing data; (the double data type holds a higher value than does a float.

Explicit casting is required when a potential exists for data loss or when converting a larger data type into a smaller data type. If you tried to place a value in a variable when the value was higher than the variable's supported data type, some data would be lost. Therefore, C# requires that these types of conversions be explicitly written using the cast operator. For instance, you can set the value of a variable declared as short to the value of a variable declared as integer using the following syntax:

short MyShortInterger;
int MyInteger = 1000;
MyShortInterger = (short) MyInteger;

Notice here that 1000 would fit in a short, so data wouldn't actually be lost if no explicit cast were performed. However, C# doesn't care; it's the potential for data loss that causes C# to require explicit casts.

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12table02 Table 12.2] lists some of the type conversions that can be done implicitly with no loss of information.

Type Can Be Safely Converted To
byte char, short, int, long, float, double, decimal
short int, long, float, double, decimal
int long, float, double, decimal
long float, double, decimal
float double, decimal
double decimal
>

Defining and Using Constants

When you hard-code numbers in your code (such as in intVotingAge = 19;), a myriad of things can go wrong. Hard-coded numbers are generally referred to as "magic numbers" because they're often shrouded in mystery; the meaning of such a number is obscure because the digits themselves give no indication as to what the number represents. Constants are used to eliminate the problems of magic numbers.

You define a constant as having a specific value at design time, and that value never changes throughout the life of your program. Constants offer the following benefits:

  • Elimination or reduction of data entry problems It is much easier, for example, to remember to use a constant named c_pi than it is to enter 3.14159265358979 everywhere that pi is needed. The compiler will catch misspelled or undeclared constants, but it doesn't care one bit what you enter as a literal value. (Incidentally, you can retrieve the value of pi using System.Math.PI, so you don't have to worry about creating your own constant!)
  • Code is easier to update If you hard-coded a mortgage interest rate at 6.785, and rates were changed to 7.00, you would have to change every occurrence of 6.785 in code. In addition to the possibility of data entry problems, you'd run the risk of changing a value of 6.785 that had nothing to do with the interest rate�perhaps a value that represented a savings bond yield. With a constant, you change the value once, and all code uses the new value.
  • Code is easier to read Magic numbers are often anything but intuitive. Well-named constants, on the other hand, add clarity to code. For example, which of the following statements makes the most sense?
decInterestAmount = ((decLoanAmount * 0.075) * 12);
  • or
decInterestAmount = ((decLoanAmount * c_fltInterestRate) * _
 c_intMonthsInTerm);

Constant definitions have the following syntax:

const datatype name = value; 

For example, to define a constant to hold the value of pi, you could use a statement such as this:

const float c_pi = 3.14159265358979;

Note how I prefix the constant name with c_. I do this so that it's easier to determine what's a variable and what's a constant when reading code. See the section on [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec5.htm#ch12lev1sec5 naming conventions] later in this hour for more information.

After a constant is defined, you can use the constant's name anywhere in code in place of the constant's value. For example, to output the result of two times the value of pi, you could use a statement like this (the * character is used for multiplication and is covered in the next hour):

Debug.WriteLine(c_pi * 2);

Using the constant is much easier and less error prone than typing this:

Debug.WriteLine(3.14159265358979 * 2);

Constants can be referenced only in the scope in which they are defined. I discuss scope in the section "[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12lev1sec4.htm#ch12lev1sec4 Determining Scope]."

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. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12fig01 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch15.htm#ch15 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.

Determining Scope

Constants, variables, and arrays are extremely useful ways to store and retrieve data in C# code. Hardly a program is written that doesn't use at least one of these elements. To properly use them, however, it's critical that you understand scope.

You had your first encounter with scope in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch11.htm#ch11 Hour 11], "Creating and Calling Methods," with the keywords private and public. You learned that code is written in procedures and that procedures are stored in modules. Scope refers to the level that a constant, a variable, an array, or a procedure can be "seen" in code. For a constant or variable, scope can be one of the following:

  • Block level
  • Method level (local)
  • Private level
graphics/bookpencil.gif Scope has the same effect on array variables as it does on ordinary variables. For the sake of clarity, I'll reference variables in this discussion on scope, but understand that what I discuss applies equally to arrays.

The different levels of scope are explained in the following sections.

 Understanding Block Scope
graphics/newterm.gif Block scope, also called structure scope, is when a variable is declared within a structure, and if so, it gives the variable block scope.

Structures are coding constructs that consist of two statements as opposed to one. For example, the standard do structure is used to create a loop; it looks like this:

graphics/bookpencil.gif C# uses the word structure to mean a user-defined type. However, when talking about code, structure is also used to mean a block of code that has a beginning and an end. For the purpose of this discussion, it is this code block that I am referring to.
do
 <statements to execute in the loop
while(i <10)

Another example is the for loop, which looks like this:

for (int I = 1; i<10;i++)
{
 <statements to execute when expression is True>
}

If a variable is declared within a structure, the variable's scope is confined to the structure; the variable isn't created until the declaration statement occurs, and it's destroyed when the structure completes. If a variable is needed only within a structure, think about declaring it within the structure to give it block scope. Consider the following example:

if (blnCreateLoop)
{
 int intCounter ;

for (intCounter=1; intCounter<=100; intCounter++)
 // Do something
}

By placing the variable declaration statement within the if structure, you ensure that the variable is created only if it is needed. In fact, you can create a block simply by enclosing statements in opening and closing braces like this:

{
 int intMyVariable = 10;
 Console.WriteLine(intMyVariable);
}
graphics/bookpencil.gif The various structures, including looping and decision-making structures, are discussed in later hours.
Understanding Method-Level (Local) Scope
graphics/newterm.gif When you declare a constant or variable within a method, that constant or variable has method-level, or local, scope. Most of the variables you'll create will have method scope. In fact, all the variables you've created in previous hours have had method-level scope. You can reference a local constant or variable within the same method, but it isn't visible to other methods. If you try to reference a local constant or variable from a method other than the one in which it's defined, C# returns a compile error to the method making the reference (the variable or constant doesn't exist). It's generally considered the best practice to declare all your local variables at the top of a method, but C# doesn't care where you place declaration statements within a method. Note, however, that if you place a declaration statement within a structure, the corresponding variable will have block scope, not local scope.
Understanding Private-Level Scope 

When a constant or variable has private-level scope, it can be viewed by all methods within the class containing the declaration. To methods in all other classes, however, the constant or variable doesn't exist. To create a constant or variable with private-level scope, you must place the declaration within a class but not within a method. Class member declarations are generally done at the beginning of the class (right after the opening brace of the class). Use private-level scope when many methods must share the same variable and when passing the value as a parameter is not a workable solution.

For all modules other than those used to generate forms, it's easy to add code to the declarations section; simply add the declaration statements just after the class declaration line and prior to any method definitions, as shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12fig02 Figure 12.2].

Figure 12.2. The declarations section exists above all declared methods.

graphics/12fig02.jpg

Classes used to generate forms have lots of system-generated code within them, so it might not be so obvious where to place private-level variables. C# inserts many private statements in classes used to build forms, so place your variable declarations after any and all form-type declaration statements in such classes (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12fig03 Figure 12.3]).

Figure 12.3. The declarations section includes the C# generated statements.

graphics/12fig03.jpg

graphics/bulb.gif In general, the smaller the scope the better. When possible, give a variable block or local scope. If you have to increase scope, attempt to make the variable a private-level variable. You should use public variables only when absolutely necessary (and there are times when it is necessary to do so). The higher the scope, the more possibilities exist for problems and the more difficult it is to debug those problems.

Naming Conventions

To make code more self-documenting (always an important goal) and to reduce the chance of programming errors, you need an easy way to determine the exact data type of a variable or the exact type of a referenced control in C# code.

graphics/bookpencil.gif Variable naming conventions have long been a hot topic. With the release of .NET, Microsoft has officially recommended that you not use naming conventions (although it's hard to imagine why). As a professional developer, I find this idea counterproductive, and most other developers I have spoken with have no plans to abandon using naming conventions. Because I so firmly believe in them and because they aid the learning process, I have used them, and I teach them in this book. Please be aware that if you don't like naming conventions, you don't have to use them. However, I strongly recommend that you do use naming conventions; the benefits they provide are considerable.
Using Prefixes to Denote Data Type 

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12table03 Table 12.3] lists the prefixes of the common data types.

Data Type Prefix Value
Boolean bln blnLoggedIn
Byte byt bytAge
Char chr chrQuantity
Decimal dec decSalary
Double dbl dblCalculatedResult
Integer int intLoopCounter
Long lng lngCustomerID
Object obj objWord
Short sho shoTotalParts
String str strFirstName
graphics/bookpencil.gif The prefix of obj should be reserved for when a specific prefix isn't available. The most common use of this prefix is when referencing Automation libraries of COM applications. For instance, when automating Microsoft Word, you create an instance of Word's Application object. Because no prefix exists specifically for Word objects, obj works just fine (that is, Word.Application objWord = new Word.Application);.
Denoting Scope Using Variable Prefixes 

Prefixes are useful not only to denote data types, they also can be used to denote scope (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#ch12table04 Table 12.4]). In particularly large applications, a scope designator is almost a necessity. Again, C# doesn't care whether you use prefixes, but consistently using prefixes benefits you as well as others who have to review your code.

Prefix Description Example
g Global g_strSavePath
m Private to class m_blnDataChanged
(no prefix) Nonstatic variable, local to method
Other Prefixes 

Prefixes aren't just for variables. All standard objects (including forms and controls) can use a three-character prefix. There are simply too many controls and objects to list all the prefixes here, although you will find that I use control prefixes throughout this book.

>

Summary

In this hour, you learned how to eliminate magic numbers by creating constants. By using constants in place of literal values, you increase code readability, reduce the possibilities of coding errors, and make it much easier to change a value in the future.

In addition, you learned how to create variables for data elements in which the initial value isn't known at design time or for elements whose values will be changed at runtime. You learned how arrays add dimensions to variables and how to declare and reference them in your code.

C# enforces strict data typing, and in this hour you learned about the various data types and how they're used, as well as tips for choosing data types and functions for converting data from one type to another. Finally, you learned about scope�a very important programming concept�and how to manage scope within your projects.

Writing code that can be clearly understood even by those who didn't write it is a worthwhile goal. Naming prefixes goes a long way toward accomplishing this goal. In this hour you learned the naming prefixes for the common data types, and you learned to use prefixes to denote scope.

Q&A
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#qad1e41129 Q1:] Are any performance tricks related to the many data types?
A1: One trick when using whole numbers (values with no decimal places) is to use the data type that matches your processor. For instance, most current home and office computers have 32-bit processors. The C# integer data type is made up of 32 bits. Believe it or not, C# can process an integer variable faster than it can process a short variable, even though the short variable is smaller. This has to do with the architecture of the CPU, memory, and bus. The explanation is complicated, but the end result is that you should usually use integer rather than short, even when working with values that don't require the larger size of the integer.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/12.htm#qad1e41139 Q2:] Are arrays limited to two dimensions?
A2: Although I showed only two dimensions (that is, intMeasurements[3,1]), arrays can have many dimensions, such as intMeasurements[3,3,3,4]. The technical maximum is 60 dimensions, but you probably won't use more than three.

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A], "Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans01 1:] What data type would you use to hold currency values?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans02 2:] Which data type can be used to hold any kind of data and essentially serves as a generic data type?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans03 3:] What values does C# support for type bool?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans04 4:] What can you create to eliminate magic numbers by defining a literal value in one place?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans05 5:] What type of data element can you create in code that can have its value changed as many times as necessary?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans06 6:] What are the first and last indexes of an array dimensioned using string_strMyArray[5]?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans07 7:] What word is given to describe the visibility of a constant or variable?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec12.htm#ch12ans08 8:] In general, is it best to limit the scope of a variable or to use the widest scope possible?
Exercises
  1. Create a project with a text box, a button, and a label control. When the user clicks the button, move the contents of the text box to a variable, and then move the contents of the variable to the Text property of the label. (Hint: a string variable will do the trick.)
  2. Rewrite the following code so that a single array variable is used rather than two standard variables. (Hint: Do not use a multidimensional array.)
string strFirstName;
string strLastName ;
strFirstName = "Allison";
strLastName = "Bermejo";