Tuesday, April 29, 2008

Introduction to Variables in c#

Introduction to Variables in c#


Variables


Definition


A computer receives information from different applications in various forms. Sometimes a person types it using the keyboard. Sometimes the user clicks the mouse. Sometimes information comes from another, more complicated source. The idea is that the computer spends a great deal of its time with various pieces of information. Information provided to the computer through a program is called datum and the plural is data. Sometimes the word data is used both for singular and plural items.

Data used by the computer comes and goes regularly as this information changes. For this reason, such information is called a variable.

When the user enters data in a program, the computer receives it and must store it somewhere to eventually make it available to the program as needed. For a program used to process employment applications, the types of information a user would enter into the program are the name, the residence, the desired salary, years of experience, education level, etc. Because there can be so much information for the same program, you must specify to the computer what information you are referring to and when. To do this, each category of piece of information must have a name.

Practical Learning: Introducing Variables



Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional
From now on, we will only refer to Microsoft Visual C#

To create a new application, on the Start Page, on the right side of Create, click Project
In the Templates section, click Console Application
Change the Name to GeorgetownCleaningServices2 and click OK
Names in C#



To name the variables of your program, you must follow strict rules. In fact, everything else in your program 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

Besides these keywords, C# has other words that should be reserved only depending on how and where they are used. These are referred to as contextual keywords and they are:

get partial set value where yield

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. For example, main is always written Main.

Values and Variables on the Console



As mentioned already, the applications we will create display in a dark object called the DOS window. Here is an example showing some values:



To display a value in this window, you can enter it in the parentheses of the Console.Write() or Console.WriteLine(). Here are two examples:

using System;

class Program
{
static void Main()
{
Console.WriteLine(248);
Console.Write(1);
}
}
If you write Console.WriteLine() with empty parentheses, an empty line would be displayed. In future lessons, we will learn what the meanings of Console, Write(), and WriteLine().

The Numeric Systems


Introduction



When a computer boots, it “loads” the operating system. If you want to use a program, you must find it either on the Start menu or from its directory and take the necessary action to open it. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who want to interact with the machine.

To write your programs, you will be using alphabetic letters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, 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, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use characters that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : “ < > ; ‘ , . /. Some of these symbols are used in the C# language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions.

Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After typing an instruction, the compiler would translate it to machine language. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in its memory using a certain amount of space for each instruction or each item you use.

There are three numeric systems that will be involved in your programs, with or without your intervention.

The Binary System



When dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system.

When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One.

The sequence of the symbols of the binary system depends on the number that needs to be represented.

The Decimal System



The numeric system that we are familiar with uses ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits.

When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion.

Decimal Values: 3849, 279, 917293, 39473
Non- Decimal Values: 0237, 0276382, k2783, R3273

The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (= 0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 101 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are:

2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751

67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048

Another way you can represent this is by using the following table:

etc Add 0 to the preceding value 1000000 100000 10000 1000 100 10 0

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s).

The Hexadecimal System



While the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the family of Latin languages consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. To produce a hexadecimal number, you use a combination of these sixteen symbols.

Examples of hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number?

From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase.
Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e
Non-Hex Numbers: 0686, ffekj, 87fe6y, 312


There is also the octal system but we will not use it anywhere in our applications.

Signed and Unsigned



The numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items.

In real life, there are numbers counted in decrement values. Such numbers start at –1 and move down to -2, -3, -4 etc. These numbers are qualified as negative.

When you write a number “normally”, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the – on the left side of the number. The – symbol is called a sign. Therefore, if the number does not have the – symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned.

Data Types



In order to use a variable in your program, the compiler must be aware of it. Once the compiler knows about a variable, it would reserve an amount of memory space for that variable


Using its name, you can refer to a particular variable when necessary. Because there are various types of variables a program can use, such as the employee's name, his home address, the desired salary, years of experience, education level, etc for our employment application analogy, the compiler needs a second piece of information for each variable you intend to use. This piece of information specifies the amount of space that a variable needs. You can see that, to store a character, such as an employee's gender (M or F) or an answer as Y or N to a question, the compiler would certainly not need the same amount of space to store the name of the last school attended by an employee.

A data type is an amount of space needed to store the information related to a particular variable.

The name of a variable allows you and the compiler to refer to a particular category of information in your program. The data type allows the compiler to reserve an adequate amount of memory space for a variable. Because you are the one who writes a program, you also tell the compiler the amount of memory space each particular variable will need. Based on this, the C# language provides categories of data types used to specify this amount of space needed for a variable.

As stated already, before using a variable, you must communicate your intentions to the compiler. Making the compiler aware is referred to as declaring the variable. To declare a variable, you have two options:

If you know the type of variable you want to use, you can provide it followed by the name of the variable. Based on this, one syntax used to declare a variable is:
DataType VariableName;


As an alternative, you can provide only a name for the variable but let the compiler specify its data type. To declare such a variable, you use the var keyword followed by the name of the variable. This certainly would not be enough. For the compiler to know how much space is necessary, you must provide a value for the variable
Providing a value for a variable is referred to as initializing it. This can be done for declared with either a data type or the var keyword:

If you declare a variable using data type, the initialization could be optional (depending on how you will access the variable)
If you declare a variable using the var keyword, you must initialize it
To initialize a variable, on the right side of its name, type the assignment operation, which is =, followed by a value:

If you declare a variable using a data type, you must initialize it with an appropriate value. When we study the data type, we will see what value is appropriate for what data type
If you declare a variable using the var keyword, you can initialize it with almost any type of value (of course there are exceptions). The purpose of using the var keyword is to let the compiler decides what type the variable is. To make this decision, the compiler refers to the type of value the variable was assigned with.
For illustrative purposes, in many lessons, we will use the var keyword to declare variables. In practicality, don't abuse or overuse the var keyword. It can be confusing. The beauty of var, which is one of its rules, is that you MUST initialize its variable. This makes it possible to know the type of variable you are using. On the other hand, if you declare too many variables with var and initialize them with the same types of values, you could get confused with the type of data that each of those variables is holding. So, use the var keyword sparingly: It can be a beauty but, if overused, it can be confusing. The good news is that the compiler knows exactly what it is doing and what it is asked to do.
Representing Numbers


A Bit



The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to represent its information. It represents data using only a 0 or 1 value:


0 1

You can represent a piece of information with one of two states. This technique of representing values is the same as the binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system.

Although the C# compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to manipulate the information stored in a bit.

The Four-Bit Combination



The single bit is used only to represent a tinny piece of information. To get effective numbers, the computer combines the bits. The first combination of bits consists of grouping four consecutive bits.



To count the bits, we number them starting at 0, followed by 1, 2, and 3. The count starts with the most right bit:



The first bit, on the right side of the group, is called the Low Order bit or LO bit. This is also called the least significant bit. The last bit, on the left side of the group, is called the High Order bit or HI bit; it is also called the most significant bit. The bit on the right side is counted as bit 0. The bit on the left side is counted as bit 3. The other bits are called by their positions: bit 1 and bit 2.

Once again, each bit can have one of two states. Continuing with our illustration, when a cup is empty, it receives a value of 0. Otherwise, it has a value of 1. On a group of four consecutive bits, we can have the following combinations:









This produces the following binary combinations: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 = 16 combinations. When using the decimal system, these combinations can be represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15.

This combination is also a system that the computer uses to count bits internally. Sometimes, in your program or in the help files, you will encounter a number that is less than four bits, such as 10 or 01 or 101. The technique used to complete and fill out the group of 4 bits consists of displaying 0 for each non-represented bit. The binary number 10 will be the same as 0010. The number 01 is the same as 0001. The number 101 is the same as 0101. This technique is valuable and allows you to always identify a binary number as a divider of 4.

When all bits of a group of 4 are 0, the combination has the lowest value, which is 0000. Any of the other combinations has at least one 0 bit, except for the last one. When all bits are 1, this provides the highest value possible for a group of 4 bits. The lowest value, also considered the minimum value, can be represented in the decimal system as 0. The highest value, also considered the maximum, can be expressed in decimal value as 24 (2 represents the fact that there are two possible states: 0 and 1; 4 represents the fact that there are four possible combinations), which is 16. This produces 16 because 24 = 16.

As you can see, the binary system can appear difficult to read when a value combines various bit representations. To make it easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:

Decimal Binary Hexadecimal
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

Table of Numeric Conversions

When looking at a binary value represented by 4 bits, you can get its decimal or hexadecimal values by referring to the table above. A group of four consecutive bits has a minimum and maximum values on each system as follows:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 15 0xf 1111

Although the C# compiler recognizes a group of four consecutive bits, you cannot store any variable in it. You can, however, manipulate the bits of the group.

A Byte


Introduction



A byte is a group or eight consecutive bits. The bits are counted from right to left starting at 0:



The most right bit is bit 0; it is called the least significant bit. It is also referred to as the Low Order bit, the LO bit, or LOBIT. The most left bit is bit 7; it is called the most significant bit. It is also referred to as the High Order bit, the HI bit, or HIBIT. The other bits are referred to following their positions:



Using the binary system, you can represent the byte using a combination of 0s and 1s. When all bits have a value of 0, the byte is represented as 00000000. On the other hand, when all bits have a value of 1, the byte is represented as 11111111. When the number grows very large, it becomes difficult to read. Therefore, you can represent bits in groups of four. Instead of writing 00000000, you can write 0000 0000. This makes the number easier to read.

If you have the patience to create combinations of bits using the boxes as we did for the group of 4, you would find out that there are 256 possible combinations. Another way to find it out is by using the base 2 technique:

27 + 26 + 25 + 24 + 23 + 22 + 21 + 20
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255

Therefore, the maximum decimal value you can store in a byte is 255.

Remember that the byte with all bits having a value of 0 has its value set to 0. Since this byte also holds a valid value, the number of combinations = 255 + 1 = 256.

When a byte is completely represented with 0s, it provides the minimum value it can hold; this is 0000 0000, which is also 0. When all bits have a value of 1, which is 1111 1111, a byte holds its maximum value that we calculated as 255 in the decimal system. As done with the group of 4 bits, we get the following table:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

The minimum storage area offered by the (Intel) computer is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents.

Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can pass it to Write() or WriteLine() and include the character between single-quotes, as follows:

using System;

class Exercise
{
static void Main()
{
Console.WriteLine('n');
}
}
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, you can use the var keyword and initialize the variable with a character in single-quotes. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Gender = 'F';

Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}
Alternatively, you can use the char keyword. Here is an example:

using System;

class Exercise
{
static void Main()
{
char Gender = 'M';

Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}
This would produce:

Student 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 an unsigned 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:

using System;

class ObjectName
{
static void Main()
{
Byte Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}
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.

Alternatively, you can also use the var keyword to declare the variable and initialize it with a small number. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}
Instead of a decimal number, you can also initialize an integral variable with a hexadecimal value. When doing this, make sure the decimal equivalent is less than 255. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Number = 0xFE;

Console.Write("Number: ");
Console.WriteLine(Number);
}
}
This would produce:

Number: 254
Press any key to continue . . .
Practical Learning: Using Bytes



Change the Program.cs file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GeorgetownCleaningServices2
{
class Program
{
static void Main(string[] args)
{
byte Shirts;
byte Pants;

Shirts = 4;
Pants = 1;

Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(Shirts);
Console.Write("Pants ");
Console.WriteLine(Pants);
Console.WriteLine("========================");
Console.WriteLine();
}
}
}


Execute the program. This would produce:
-/- Georgetown Cleaning Services -/-
========================
Item Type Qty
------------------------
Shirts 4
Pants 1
========================


Close the DOS window
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:

using System;

class NumericRepresentation
{
static void Main()
{
sbyte RoomTemperature = -88;

Console.Write("When we entered, the room temperature was ");
Console.WriteLine(RoomTemperature);
Console.WriteLine();
}
}
This would produce:

When we entered, the room temperature was -88
A Word


Introduction



A word is a group of 16 consecutive bits. The bits are counted from right to left starting at 0:



Considered as a group of 16 bits, the most right bit of a word, bit 0, is called the least significant bit or Low Order bit or LO bit or LOBIT. The most left bit, bit 15, is called the most significant bit or High Order bit or HI bit or HIBIT. The other bits are referred to using their positions: bit 1, bit 2, bit 3, etc.

Considering that a word is made of two bytes, the group of the right 8 bits is called the least significant byte or Low Order byte or LO byte or LOBYTE. The other group is called the most significant byte or High Order byte or HI byte or HIBYTE.

The representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits by 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The minimum decimal value of a word is 0. The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0.

The maximum binary value represented by a word is 1111 1111 1111 1111. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1:

1*215+1*214+1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

= 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

= 65535

To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F:

1111 1111 1111 1111
f f f f
= 0xffff
= 0xFFFF
= 0Xffff
= 0XFFFF


Short Integers



A word, which is a group of 16 contiguous bits or 2 bytes, can be used to hold a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. To declare a variable for such a value, you can use the var keyword and initialize the variable with a value between –32768 to 32767. Here is an example:

using System;

class Exercise
{
static void Main()
{
var SchoolEffective = 1400; // Number of Students

Console.Write("School Effective: ");
Console.WriteLine(SchoolEffective);
}
}
This would produce:

School Effective: 1400
Press any key to continue . . .
Since the byte is used for characters and very small numbers, whenever you plan to use a number in your program, the minimum representation you should use is a word.

A natural number is also called an integer. If you want to declare the variable using a data type, the smallest integer you can store in a word is declared with the short keyword. Because a short integer is signed by default, it can store a value that ranges from –32768 to 32767. Here is an example program that uses two short integers:

using System;

class Exercise
{
static void Main()
{
short NumberOfPages;
short Temperature;

NumberOfPages = 842;
Temperature = -1544;

Console.Write("Number of Pages of the book: ");
Console.WriteLine(NumberOfPages);
Console.Write("Temperature to reach during the experiment: ");
Console.Write(Temperature);
Console.WriteLine(" degrees\n");
}
}
This would produce:

Number of Pages of the book: 842
Temperature to reach during the experiment: -1544 degrees
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 either the var of 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:

using System;

class NumericRepresentation
{
static void Main()
{
// These variables must hold only positive integers
ushort NumberOfTracks;
ushort MusicCategory;

NumberOfTracks = 16;
MusicCategory = 2;

Console.Write("This music album contains ");
Console.Write(NumberOfTracks);
Console.WriteLine(" tracks");
Console.Write("Music Category: ");
Console.Write(MusicCategory);
Console.WriteLine();
}
}
This would produce:

This music album contains 16 tracks
Music Category: 2
Practical Learning: Using Unsigned Short Integers



To use unsigned short integers, change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GeorgetownCleaningServices2
{
class Program
{
static void Main(string[] args)
{
byte Shirts;
byte Pants;
ushort OtherItems;

Shirts = 4;
Pants = 1;
OtherItems = 3;

Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(Shirts);
Console.Write("Pants ");
Console.WriteLine(Pants);
Console.Write("Other Items ");
Console.WriteLine(OtherItems);
Console.WriteLine("========================");
Console.WriteLine();
}
}
}


Execute the program. This would produce:
-/- Georgetown Cleaning Services -/-
========================
Order Date: 7/15/2002
------------------------
Item Type Qty
------------------------
Shirts 4
Pants 1
Other Items 3
========================

Press any key to continue . . .


Close the DOS window

Introduction to C#

Introduction to C#

Introduction


C# is a Sharp C


C#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. This is a universal language that is used on many operating systems, including Microsoft Windows. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer.

Console Applications




The C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window. Those are the types of applications we will create in our lessons.

To study the C# language, we will use Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional. To get Microsoft Visual C# 2008 Express Edition, you can download it free from the Microsoft web site. After downloading it, you can install it.

To launch Microsoft Visual C# 2008 Express Edition, you can click Start -> (All) Programs -> Microsoft Visual C# 2008 Expression Edition:



To launch Microsoft Visual C# 2008 Professional, you can click Start -> (All) Programs -> Microsoft Visual Studio 2008. To create the type of applications we will study in our lessons, on the main menu, you can click File -> New Project... In the Templates section of the New Project dialog box, you can click Console Application, accept the default name or change it:



After clicking OK, a skeleton code would be created for you. Right now, we will not review every part of the code. Everything will be introduced and explained as we move on.

Writing Code


Introduction



The programs we will write are meant to give instructions to the computer about what to do, when to do something, and how to do it. You write these instructions in an easy to understand English format, using words we will study. This means that a regular instruction uses normal text with alphabetic characters, numbers, and non-readable symbols. Normally, you can write your instructions using any text editor such as Notepad, WordPad, WordPerfect, or Microsoft Word, etc. When writing your instructions, there are rules your must follow and suggestions you should observe. We sill study each one of them as we move on.

The group of instructions used by your program is also referred to as code. To assist you with writing code, Microsoft Visual C# 2008 includes a text editor referred to as the Code Editor. This is the window that displays when you have just created a console application. Besides the Code Editor, the integrated development interface (IDE) of the Microsoft Visual C# 2008 is made of various parts, which we will review when necessary.

Practical Learning: Creating a Program



Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional
To create a new application, on the Start Page, on the right side of Create, click Project
In the Templates section, click Console Application
Change the Name to GeorgetownCleaningServices1 and click OK
Comments



A comment is a line or paragraph of text that will not be considered as part of your code of a program. There are two types of comments recognized by C#.

To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:

// This line will be ignored. I can write in it anything I want
The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination of /* and */ would not be read. Therefore, you can use this technique to span a comment on more than one line.

Practical Learning: Creating Comments



To create comments, change the file as follows:
using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
/*
namespace GeorgetownCleaningServices1
{*/
class Program
{
static void Main(/* string[] args */)
{
}
}
//}


To save the project, on the Standard toolbar, click the Save All button


Accept the name as GeorgetownCleaningServices1 and click Save
Code Colors



Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text. The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:



In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

Indentation



Indentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.

Solution and Project Management


A Project



We have seen how to create a console application. Microsoft Visual C# allows you to create various other types of applications. This is why you should first display the New Project dialog box to select your option. Besides console applications, in future lessons, we will start some applications with the Empty Project. We will also learn how to create a library using the Class Library option. We will ignore the other three options in this book.

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, expand C#, followed by Formatting and click Indentation. Then change the options on the right side:



After making the changes, click OK to validate or Cancel to ignore.

Saving a Project



In previous versions of Microsoft Visual C# (namely 2002 and 2003), you always had to formally create a project in order to use one and you always had to save it. After realizing that many of the projects that developers or students create are for experimental purposes, Microsoft provided the ability to only temporarily create a project, then to save it or not. Saving a project allows you to keep on a medium so you can refer to it later.

When Microsoft Visual Studio 2008 (any edition) is installed, it creates a folder named Visual Studio 2008 in your My Documents folder. The My Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2008 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

A Solution



A solution is used to coordinate the different aspects of an application that is being created. When you create a project, it represents one detail of the application you have in mind. Besides the code you are writing, you may want to add other items. Instead of one project, in the next sections, we will see that a solution can contain more than one project.

When creating a project, the solution holds the same name as the project. You can see their names in the Solution Explorer:



The solution and a project can have different names. While working on a project, to rename the solution, in the Solution Explorer, you can click the first node, which is the name of the solution starting with Solution. Then, in the Properties window, click (Name) and type the name of your choice:



This name is temporary, especially if you have not yet saved the project. If you want to permanently save a solution for later use, there are two techniques you can use.

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:



When you save a project (for the first time), by default, Microsoft Visual C# creates a new folder for it in the My Documents\Visual Studio 2008\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Executing a Project



After creating a project and writing code, you may want to see the result. To do this, you must execute the application. This would create an executable that you can use on other computers and that you can distribute to other people.

To execute an application, on the main menu, you can click Debug -> Start Without Debugging. Instead of going through the main menu every time, you can add the Start Without Debugging button to a toolbar. To do this, you can right-click any toolbar and click Customize... In the Commands property page of the Customize dialog box, you can click Debug in the Categories click, then drag Start Without Debugging, and drop it on a toolbar. Here is an example:



After adding the button(s), you can click Close. The next time you want to execute an application, you can just click this button.

Practical Learning: Executing an Application



To execute the application, on the main menu, click Debug -> Start Without Debugging
After viewing the result in a DOS window, press Enter to close it
Adding a Project



One of the most valuable features of Microsoft Visual Studio 2005 is that it allows you to work on more than one project without launching more than one instance of the studio. This means that you can add a project to another project you are working on and treat each as a separate entity.

Before adding one project to another, you must save, or you must have saved, the current project. To add a project, in the Solution Explorer, you can right-click the most top node (it starts with Solution) and position the mouse on Add:



If you have a project that was previously saved but you don't want to open a separate instance of Microsoft Visual Studio for it, you can click Existing Project... This would bring the Add Existing Project dialog box that allows you to select a project from a folder.

To add a new project, after right-clicking, you can click New Project... If you add a new project, and if you want to keep it for future references, you must save it. To save the new project, you can click the Save All button on the Standard toolbar. After saving the new project, a folder with its name would be created inside of the folder of the solution.

On the right side of the name of the solution in Solution, the number of its projects is specified in parentheses, as 1 project, or 2 projects, etc.

After adding a project, each would be represented by its own node in the Solution Explorer and in the Class View. Here is an example:



Also, a sub-folder for each project is created in the folder of the solution:



In the Solution, the name of one of the projects, if there is more than one, is in bold characters. This project is called the StartUp Project. If, on the main menu, you click Debug -> Start Without Debugging, the project in bold characters would be executed. If you want to change the start up project, you can right-click its node and click Set As StartUp Project.