Learning Resources
Â
Variables and Data Types
A web page whose main purpose is to display regular text and images to the browser is suited for HTML tags only. To make the page more interesting, you and your users can exchange information, as illustrated in the previous lesson. For example, you may want your users to submit values to the server, let the server either store those values or analyze them and send some results to the user. This interact usually means that, in the beginning, you would not know the type of value(s) that one visitor would submit as opposed to another user. Based of this, you must prepare storage areas on the server's computer memory to temporarily hold the values used during a visitor's interaction with your web page. This type of storage area is called a variable.
As there are different types of values used in an application, there are also different requirements to store those values. Fortunately, to store a value in a memory, you must provide only two pieces of information: the name of the variable and the type of information that would be stored in the memory reserved for that variable.
The Name of a Variable
To specify the name of a variable, there are rules you must follow:
- The name of a variable must start with either a letter or an underscore. A name can have only one letter but if you start it with an underscore, then the underscore must be followed by a letter
- After the first character as an underscore or a letter, the name can contain letters, digits, or underscores in any combination
- The name must not contain space but it can be made of various words as long as these words are concatenated (added together to produce one word)
- The name must not contain any symbol other than letters, digits, or underscores
After respecting these rules, you can adopt a naming convention that suits you.
Names in C#
To name the variables of your program, you must follow strict rules. In fact, everything else in your application must have a name. C# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords. They are:
abstract | const | extern | int | out | short | typeof |
as | continue | false | interface | override | sizeof | uint |
base | decimal | finally | internal | params | stackalloc | ulong |
bool | default | fixed | is | private | static | unchecked |
break | delegate | float | lock | protected | string | unsafe |
byte | do | for | long | public | struct | ushort |
case | double | foreach | namespace | readonly | switch | using |
catch | else | goto | new | ref | this | virtual |
char | enum | if | null | return | throw | void |
checked | event | implicit | object | sbyte | true | volatile |
class | explicit | in | operator | sealed | try | while |
Once you avoid these words, there are rules you must follow when naming your objects. On this site, here are the rules we will follow:
- The name must start with a letter or an underscore
- After the first letter or underscore, the name can have letters, digits, and/or underscores
- The name must not have any special characters other than the underscore
- The name cannot have a space
Besides these rules, you can also create your own but that abide by the above. C# is case-sensitive. This means that the names Case, case, and CASE are completely different.
Data Types
Â
Characters
In the English alphabet, a character is one of the following symbols: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "
Besides the English language, other languages use other or additional characters that represent verbal or written expressions.
C# recognizes that everything that can be displayed as a symbol is called a character. To declare a variable whose value would be a character, use the char keyword. Here is an example:
char Gender = 'M';
Escape Sequences
An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n.
An escape can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n".
The C# language recognizes other escape sequences.
Escape Sequence | Name | Description |
\a | Bell (alert) | Makes a sound from the computer |
\b | Backspace | Takes the cursor back |
\t | Horizontal Tab | Takes the cursor to the next tab stop |
\n | New line | Takes the cursor to the beginning of the next line |
\v | Vertical Tab | Performs a vertical tab |
\f | Form feed | Â |
\r | Carriage return | Causes a carriage return |
\" | Double Quote | Displays a quotation mark (") |
\' | Apostrophe | Displays an apostrophe (') |
\? | Question mark | Displays a question mark |
\\ | Backslash | Displays a backslash (\) |
\0 | Null | Displays a null character |
 To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.
The Byte Data Type
A byte is a number whose value can range from 0 to 255 and therefore can be stored in one byte. You can use it when you know a variable would hold a relatively small value such as people's age, the number of children of one mother, etc. To declare a variable that would hold a small natural number, use the byte keyword. Here is an example:
byte Age;
You can initialize a byte variable when declaring it or afterwards. Here is an example that uses the byte data type:
Byte Age = 14;
Make sure you do not use a value that is higher than 255 for a byte variable, you would receive an error. When in doubt, or when you think that there is a possibility a variable would hold a bigger value, don't use the byte data type as it doesn't like exceeding the 255 value limit.
Signed Byte
A byte number is referred to as signed if it can hold a negative of a positive value that ranges from -128 to 127, which can therefore fit in a byte. To declare a variable for that kind of value, use the sbyte keyword. Here is an example:
sbyte RoomTemperature = -88;
Short Integers
A natural number is also called an integer. To use a variable that would hold such a number, you can declare it using the short keyword followed by a name. A variable declared as short can hold a value that ranges from –32768 to 32767. Here are two examples:
short NumberOfPages;
short Temperature;
NumberOfPages = 842;
Temperature  = -1544;
Because a short integer handles numbers that are larger than the signed byte, any variable you can declare for a signed byte can also be declared for a short variable.
Unsigned Short Integers
If a variable must hold positive and relatively small numbers, it is referred as an unsigned short integer. Such a variable can be declared using the ushort keyword. An unsigned short integer can hold numbers that range from 0 to 65535 and therefore can fit in 16 bits. Here is an example:
// These variables must hold only positive integers
ushort NumberOfTracks;
ushort MusicCategory;
NumberOfTracks = 16;
MusicCategory = 2;
To use a variable that would hold quite large numbers, declare it using the int keyword. A variable declared as int can store values between –2,147,483,648 and 2,147,484,647 negative or positive. Here is an example:
int CoordX;
int CoordY;
  Â
CoordX = 12;
CoordY = -8;
Unsigned Integers
If the variable must hold only positive natural numbers, you can declared it using the uint keyword. The uint keyword is used for a variable that can hold positive numbers whose value would range from 0 to 2,147,484,647. Here are examples:
uint DayOfBirth;
uint MonthOfBirth;
uint YearOfBirth;
  Â
DayOfBirth  = 8;
MonthOfBirth = 11;
YearOfBirth = 1996;
Long Integers
To use a variable that can hold very large numbers, declare it using the long keyword.
Here is an example that uses the long data type:
long CountryArea;
     Â
CountryArea = 5638648;
Although the long data type is used for large number, it mainly indicates the amount of space available but you don't have to use the whole space. For example, you can use the long keyword to declare a variable that would hold the same range of numbers as the short, the int, or the uint data types. If you declare a variable as long but use it for small numbers, the compiler would allocate the appropriate amount of space to accommodate the values of the variable. Consequently, the amount of space made available may not be as large as required. If you insist and want the compiler to reserve the whole space required for a long variable, when assigning a value to the variable, add an L suffix to it. Here is an example:
long CountryArea;
     Â
CountryArea = 5638648L;
Keep in mind that an int, a uint, a short, or a ushort can fit in a long variable.
Unsigned Long Integers
In some cases, you will need a variable to hold only positive, though large, numbers. To declare such a variable, you can use the ulong data type. A variable declared as ulong can handle very large positive numbers that range from 0 to 18,446,744,073,709,551,615.
Introduction to Real Numbers
A real number is a number that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel. On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.
Floating-Point Numbers With Single Precision
The integers we have used so far have the main limitation of not allowing decimal values. C# provides floating values that would solve this problem. The most fundamental floating variable is declared with the float keyword. A variable declared a float can store real numbers that range from ±1.5 × 10−45 to ±3.4 × 1038 with a precision of 7 digits in 32 bits. Here is an example:
float Distance;
Floating-Point Numbers With Double Precision
When a variable is larger than the float can handle and requires more precision, you should declare it using the double keyword. A variable declared as double can store very large numbers ranging from ±5.0 × 10−324 to ±1.7 × 10308 with a precision of 15 or 16 digits.
Here is an example:
double StudentAge;
     Â
StudentAge = 14.50;
Because the double data type provides a better result with a better precision than the float, whenever you declare a variable as float and assign it a value as we did earlier, the compiler reserves very large memory space that can store the values of the variable. If you insist on the variable being treated as float, when assigning it a value, add an F suffix to the value. Here is an example:
float Distance;
     Â
Distance = 248.38F;
Decimal
The decimal data type can be used to declare a variable that would hold significantly large values. You declare such a variable using the decimal keyword. The values stored in a decimal variable can range from ±1.0 × 10−28 to ±7.9 × 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the decimal data type is suitable for currency values.
After declaring a decimal variable, you can initialize it with a natural number. To indicate that the variable holds a decimal value, when initializing it, add an M suffix to its value. Here is an example:
decimal HourlySalary;
     Â
HourlySalary = 24;
Accessory Data Types
Â
Strings
A string is an empty space, a character, a word, or a group of words that you want the compiler to consider "as is", that is, not to pay too much attention to what the string is made of, unless you explicitly ask it to. This means that, in the strict sense, you can put in a string anything you want. Primarily, the value of a string starts with a double quote and ends with a double-quote. An example of a string is "Welcome to ASP.NET development".
Sometimes, you will need to use a string whose value is not known in advance. Therefore, you can first declare a string variable. To do this, use the string keyword followed by a name for the variable. The name will follow the rules we defined above. An example of a string declaration is:
string Msg;
After declaring a string, you can give it a primary value by assigning it an empty space, a character, a symbol, a word, or a group of words. The value given to a string must be included in double-quotes. Here are examples of string variables declared and initialized:
string Empty = "";
string Gender = "F";
string FName = "Nelson Mandela";
string Msg   = "Welcome to the World of C# Programming! ";
Dates and Times
A date is a unit that measures the number of years, months, or days elapsed in a specific period. A time is a unit that counts the number of seconds that have elapsed since midnight of the day considered. Although dates and times are large subjects that would require a detailed study, at this time, we will consider them in simple terms.
To declare a variable that would hold date or time values, use the DateTime data type. Here is an example:
DateTime DateHired;
The .NET Framework sets its starting periodic date to January 1, 0001 at midnight (12:00:00 or 0:00 AM). If not assigned a specific value, the variable is initialized to 1/1/0001 at midnight.
Objects
The object data type is used to declare a variable whose type is not primarily defined and can be any of the other data types we have introduced. Here is an example:
object Whatever;
After creating an object variable, you can use its value as you see fit.
Constants
Â
Custom Constants
Suppose you intend to use a number such as 39.37 over and over again. If you use this 39.37 many times in your program, at one time, you may make a mistake and type it as 3937 or 3.937 or else. Because of mistakes in the way to represent the number, the same calculation produces different results. To make sure that this is unlikely, you can instead use a variable that holds the value. Then, when you need that value, you can access the variable instead of the value itself. A number such as 39.37 is called a constant.
A constant is a value that never changes such as 244, "ASEC Mimosa", 39.37, or True. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.
To create a constant, type the const keyword to its left. When declaring a constant, you must initialize it with an appropriate value. Here is an example:
const double ConversionFactor = 39.37;
Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. To initialize a constant variable, the value on the right side of the assignment operator "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.
Built-in Constants
There are two main categories of constants you will use in your programs. You can create your own constant as we saw above. The C# language also provides various constants. Some constants are part of the C# language. Some other constants are part of the .NET Framework. Before using a constant, of course, you must first know that it exists. Second, you must know how to access it. A constant that is part of the C# language can be accessed anywhere in your code. Those constant are normally defined in the System namespace. Other constant are defined in various appropriate namespaces.
null: The null keyword is a constant used to indicate that a variable doesn't hold a known value
PI: PI is a constant used as the ratio of the circumference of a circle to its diameter. PI is defined in Math. To use it, you would type Math.PI.
Â