C Sharp Variables and Constants

Revision as of 16:39, 14 January 2008 by Neil (Talk | contribs) (Casting Variable Types in C#)

Revision as of 16:39, 14 January 2008 by Neil (Talk | contribs) (Casting Variable Types in C#)

It is impossible to gain proficiency in any programming language without first learning some of the basics. Perhaps the most basic aspect of programming involves the use of variables and constants. Even the most advanced and impressive programs, from high end video games to enterprise commerce applications, use variables in one form or another. In this chapter of C# Essentials we will cover everything that a C# programmer needs to know about variables and constants.

What is a C# Variable?

Variables are essentially locations in computer memory that are reserved for storing the data used by an application. Each variable is given a name by the programmer and assigned a value. The name assigned to the variable may then be used in the C# code to access the value assigned to the variable. This access can involve either reading the value the variable, or changing the value. It is, of course, the ability to change the value of variables which gives them the name variable.

A variable must be declared as a particular type such as an integer, a character or a string. C# is what is known as a strongly typed language in that once a variable has been declared as a particular type it cannot subsequently be changed to a different type. While this may come as a shock to those familiar with loosely typed languages such as Ruby it will be familiar to Java, C and C++ programmers. Whilst it is not possible to change the type of a variable it is possible to disguise the variable as another type under certain circumstances. This involves a concept known as casting and will be covered later in this chapter.

Variable declarations require a type, a name and, optionally a value assignment. The following example declares an integer variable called interestRate but does not initialize it:

int interestRate;

The following example declares and initializes a variable using the assignment operator (=):

int interestRate = 10;

A new value may be assigned to a variable at any point after it has been declared.

int interestRate = 5; //Declare the variable and initialize it to 5

interestRate = 10; // variable now equals 10

interestRate = 20; // variable now equals 20

What is a C# Constant?

A constant is similar to a variable in that it provides a named location in memory to store a data value. Constants differ in one significant way in that once a value has been assigned to a constant it cannot subsequently be changed.

Constants are particularly useful if there is a value which is used repeatedly throughout the application code. Rather than use the value each time, it makes the code easier to read if the value is first assigned to a constant which is then referenced in the code. For example, it might not be clear to someone reading your C# code why you used the value 5 in an expression. If, instead of the value 5, you use a constant named interestRate the purpose of the value becomes much clearer. Constants also have the advantage that the if the programmer needs to change a widely used value it only needs to be changed once in the constant declaration and not each time it is referenced.

As with variables, constants have a type, a name and a value. Unlike variables, constants must be initialized at the same time that they are declared and must be prefixed with the const keyword:

const int interestRate = 10;

Note that a constant, unlike a variable, must be initialized at the point that it is declared. For example, the following code:

const int interestRate; // Invalid - a const must be initialized at creation time

will result in a compilation error along the lines of A const field requires a value to be provided. Now that we have described C# variables and constants it is time to start looking at the different types that are available to us as C# programmers.


C# Integer Variable Types

Perhaps the most widely used of the variable types is the integer. C# provides a number of different integer types based on number size and whether the integers are signed (positive only) or unsigned (positive or negative). All the integer variable types have one thing in common and that is that they may only be used to store whole numbers.

The following table lists the various C# integer variable types together with details of the number of bytes of physical memory consumed by each type and the acceptable value ranges.

TypeSize in BytesValue Range
byte1 byte0 to 255
sbyte1 byte-128 to 127
short2 bytes-32,768 to 32,767
ushort2 bytes0 to 65,535
int4 bytes-2,147,483,648 to 2,147,483,648
uint4 bytes0 to 4,294,967,295
long8 bytes-1020 to 1020
long8 bytes0 to 2 x 1020

C# Floating Point Variables

Integers are fine for dealing with whole numbers but of little use when there are numbers after the decimal point. Such numbers may be stored in float or double variable types. The default type for such numbers is double. The following table shows the two types with comparisons of the number ranges supported and the number of significant digits in each case:

TypeSize in BytesValue RangeDigit Accuracy
float8 bytes1.5 * 10-45 to 3.4 * 1038 6 - 7 digits
double16 bytes5.0 * 10-324 to 1.7 * 1030815 - 16 digits

It is important to note that float and double variables cannot be used as counting variables (for example in looping constructs).

The C# Decimal Variable Type

Both the integer and floating point families of C# variable types have some limitations. Integers can only handle whole numbers, resulting in the fractional part of a value being stripped off. Floats, on the other hand, have problems with rounding accuracy. Clearly the best of both worlds is sometimes needed and to address this requirement the decimal variable type is provided. The decimal type is a compromise between integers and float variable types in that it can store fractional parts of a value and provide exact values in computations.

The decimal variable type is capable of holding values in the range 10-28 all the way up to 1028 with none of the rounding problems associated with floating point variable types.

C# Boolean Variable Type

The C# variable type is declared using the bool keyword and allows for the storage of true and false values. Boolean variables are particularly useful in flow control constructs such as if and while statements.

Unlike some other programming languages, C# boolean variables must be assigned either true or false and cannot be assigned 1 or 0:

bool loopFinished = false;

loopFinished = true;

C# Character Variable Type

When we talk about characters we are referring to individual letters and numbers. For example, the letter 'a' is a character, as is the visual representation of the number '1'. Such characters may be stored in a C# char variable. A char variable can contain one character and one character only. It is important to be aware that a character is not limited to those in the English alphabet. A character stored in a char variable can be Chinese, Japanese, Arabic, Cyrillic, Hebrew or any other type of character you care to mention.

In addition, characters can be used for counting in loops and even in mathematical expressions. To assign a character to a variable simply surround the character with singe quotes:

char myLetter = 'a';

C# provides a number of special character constants which have a special meaning when displayed. These special constants perform such tasks as displaying tab and new lines in text. The following table lists the characters, all of which are identified by a preceding backslash (\):

Character ConstantSpecial Value
\nNew Line
\tTab
\0Null
\rCarriage Return
\\Backslash

Note that there is a special character sequence for the Backslash (\\). Because the special characters begin with a backslash the compiler interprets any instances of a single backslash as the pre-cursor to a special character. This raises the question of what to do if you really want a backslash. The answer is to use the double backslash special constant sequence.

C# String Variables

In the preceding section we looked at storing individual characters in a char variable. Whilst this works for storing a single letter or number it is of little use for storing entire words or sentences. For this purpose the string variable type is supported by C#. Variables of type string can store a string of any number of characters.

String values are surrounded by double quotes ("). For example:

string myString = "This is a string";

A string declaration in C# cannot be spread over multiple lines. If a string needs to be split over multiple lines by new lines the \n special character can be used. For example:

string myString = "This is line one\nThis is line two\nThis is line 3";

System.Console.WriteLine (myString);

The above example code will result in the following output:

This is line one
This is line two

As a matter of fact, any of the special characters outlined in the preceding section on the char type may be embedded into string.

Casting Variable Types in C#

In instances where it is safe to do so without data loss C# will allow you to assign a value from one type of variable to another simply using the assignment operator. For example, since a long variable is quite capable of storing any value that can be stored in an int variable an assignment such as the following is perfectly valid:

int myInteger = 20;
long myLong;

myLong = myInteger;

The same is not true of assigning a long to an int since a long is capable of storing significantly larger numbers than an int (an int is 4 bytes long versus 8 bytes for a long). Attempting to squeeze a long into an int value would inevitably result in lost data. For this reason the C# compiler will flag such an attempt as an error and stubbornly refuse to compile the code.

It is just possible, however, that you as the programmer know that even though a variable is a long type that it will never contain a value greater than an int is capable of storing. In this case you might legitimately want to assign the value stored in a long variable to an int variable. This can be achieved by using a cast to convert the long value.

Casts are performed by placing the variable type to which you wish to convert before the name of the variable you wish to convert from. For example, to convert a long value to an int during an assignment operation:

int myInteger;
long myLong = 1232;

myInteger = (int)myLong;

Note that casting is only possible on numerical data types. It is not, therefore, possible to perform casts on string, or bool variables.