C# Tutorial : Lesson 09 – Constructors & Destructors

August 6th, 2007
The need for Initialization

A class contains data members (variables) and member functions. Initializing the values of these data members is essential, at times. Take a look at the following scenarios:-

1
2
int MyNumber;
Console.WriteLine("My Number = {0}", MyNumber);

This block of code declares a variable MyNumber and then prints it on the screen. However, when you try to execute these instructions, an error Use of unassigned local variable ‘Product’ will be generated. This is because, we are trying to use the value of MyNumber, even before we have assigned it one. This is where initialization comes in. Many languages do implicit initialization based on the type of these atomic (int, char, bool, string, etc) data types. Example: 0 for int, false for bool, “” or NULL string for string. But, a strongly typed language like C# doesn’t. The corrected code would be as follows:-

1
2
int MyNumber = 10;
Console.WriteLine("My Number = {0}", MyNumber);

Take a look at this code snippet.

1
2
3
4
5
6
int Product;
for (int I = 1; I <= 10; I++)
{
    Product *= I;
}
Console.WriteLine("The product of the first 10 natural numbers is {0}", Product);

This block of code is meant to calculate the product of the first 10 natural numbers. For this, we have setup a loop running from 1 to 10 and declared a variable named Product to store the running product. Finally, we display the result using Console.WriteLine. Again, this block of code generates an error on line 4. This is because, we haven’t initialized the value of Product. The expression Product *= I is equivalent to Product = Product * I. When this expression is being evaluated for the first time, the Right Hand Side (RHS) part will be evaluated first. This generates the error because at the moment, Product has no value.

In the previous versions of VB (not VB .NET), the value for Product would have been automatically set to 0. While, this would take care of this error, a logical error would creep in and drive the calculations crazy – the product of first 10 natural numbers = 0. To correct this, Product must be initialized to 1. In situations like these, an initialization is a must. Here’s the corrected code:-

1
2
3
4
5
6
int Product = 1;
for (int I = 1; I <= 10; I++)
{
    Product *= I;
}
Console.WriteLine("The product of the first 10 natural numbers is {0}", Product);
Initializing Data Members

Data members can be initialized in a similar fashion:-

1
2
3
4
class MyClass
{
    int MyNumber = 69;
}

However, its a better approach to have a method do all initializations inside a class.

1
2
3
4
5
6
7
8
9
class MyClass
{
    int MyNumber;
 
    public void Initialize()
    {
        MyNumber = 69;
    }
}

After instantiating the object of this class, the method Initialize would have to be called to set the initial value for MyNumber.

1
2
MyClass ClassA = new MyClass();
ClassA.Initialize();

This approach has a disadvantage too. The Initialize method needs to be called explicitly following the object instantiation. This is where the constructor jumps in. To define it: A Constructor is a special method which bears the same name as that of the class it is in and is used for initializing the data members of the class. Summing up the important properties of the constructor:-

  • A Method having the same name as that of the class it is defined in.
  • It does not return any value. Also, it doesn’t have a return type associated with it, not even void.
  • It is used for initializing the data members.
  • A class can have multiple constructors.
  • It is automatically invoked when the class is instantiated.

Here is how the previous example would look when done with constructors.

1
2
3
4
5
6
7
8
9
class MyClass
{
    int MyNumber;
 
    public MyClass()
    {
        MyNumber = 69;
    }
}

Now, when the class is instantiated, the method MyClass() will be automatically invoked and MyNumber will be assigned the value 69.

Static & Instance Constructors

Constructors can either be associated with a class’s instance (object) or the class itself. Instance constructors are the ones associated with the object and are invoked when an object of the class is instantiated. They can be used to initialize the non static members of the class. The above example was that of an instance constructor.

Static constructors on the other hand, are invoked only once during the execution of the program and can be used to initialize the static variables.

Example:-

1
2
3
4
5
6
7
8
9
public class MyClass
{
	static int MyNumber;
 
	static MyClass()
	{
		MyNumber = 69;
	}
}

A class can have these two constructors existing simultaneously:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    public class MyClass
    {
        static int MyNumber;
        int YourNumber;
 
        static MyClass()
        {
            MyNumber = 69;
        }
 
        MyClass()
        {
            YourNumber = 69;
        }
    }

Note: Static constructors can’t be used to initialize non-static variables and Instance constructors can’t be used to initialize static variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    public class MyClass
    {
        static int MyNumber;
        int YourNumber;
 
        static MyClass()
        {
            YourNumber = 69;  // Error: YourNumber is not a static member
        }
 
        MyClass()
        {
            MyNumber = 69;  // Error: MyNumber is a static member
        }
    }
Parameterized Constructor

The instance constructors we have seen up until this point are all default constructors. They initialize the variables with hard-coded values and are hence not flexible. We can use parameterized constructors to overcome this problem. Parameterized constructors as the name suggests, take parameters with which they initialize the values of the member variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass ClassA = new MyClass(69);
        }
    }
 
    public class MyClass
    {
        int MyNumber;
 
        public MyClass(int Number)
        {
            this.MyNumber = Number;
        }
    }
}

Multiple, parameters can be supplied by separating each of them with a comma. The this keyword can be used to get a reference to the current instance of a class.

Destructors

That which can be created, can be destroyed. Hence came the destructor which has the same name as that of the class it is in and is prefixed by a tilde (~) symbol. Destructors are automatically invoked when the instance of the class is destroyed. They are ideally used to release any memory occupied by the member objects. The .NET Framework automatically manages the memory for the atomic data types (int, string, char, etc). However, user defined data types are managed using a safe mechanism which does not release the memory occupied by an object unless all references to it are destroyed. This can be done in the class destructor. The following example, instantiates an object of the Socket class (located in the System.Net.Sockets namespace) inside the constructor and closes it inside the destructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    class MyClass
    {
        System.Net.Sockets.Socket Sck;
 
        MyClass()
        {
             Sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
 
        ~MyClass()
        {
            Sck.Close();
        }
    }
Garbage Collection

The .NET Framework isolates the programmers from having to handle memory requirements. Garbage collection is the process of releasing the memory occupied by unused objects. Unlike, C++ there is no delete keyword in C# and objects cannot be explicitly destroyed. This job is automatically carried out by a special program of the .NET Framework known as the Garbage collector(GC). This program periodically scans the application for objects with no references and marks them for deletion. It is the GC which determines when the destructor of an object is invoked. This way, the GC ensures that only unused objects get destroyed.

Finalize() Method

This method allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

Source: MSDN

This method is invoked when all of the references to an object are released from the memory. It does nothing by default and needs to be overridden. However, the precise timing of when the Finalize method would be invoked cannot be predicted. The CLR utilizes a system called reference-tracing Garbage collection, where by the GC periodically looks for objects that have no references left. Once such an object is found, the CLR invokes the Finalize method for the object, following which, the memory occupied by the object is released.

Dispose() Method

All classes that implement the IDisposable interface must define the Dispose() method. This method is to be used to perform application-defined tasks associated with freeing, releasing, or resetting unmanaged resources like Database connections, etc. Unlike, the Finalize() method, the Dispose() method is not automatically called and it must be explicitly called when the object is no longer in needed.

Fore more information on the Garbage Collection process, read this article written by Jeffrey Richter.

C#

C# Tutorial : Lesson 08 – Functions/Methods

July 24th, 2007

The programming model has gone through many refinements, each change improving upon the model. One of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these are fragments of code within a program. They offer the following advantages:-

  • Reduction of code duplication by offering re-usability
  • Simplifying program logic by decomposing the program into smaller blocks
  • Improving readability of the program
Why do we need functions?

Consider the following program:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int JoinDay;
 
            Console.WriteLine("Enter the day of Joining:");
            JoinDay = Convert.ToInt32(Console.ReadLine());
 
            switch (JoinDay)
            {
                case 1:
                    Console.WriteLine("You Joined on a Sunday");
                    break;
 
                case 2:
                    Console.WriteLine("You Joined on a Monday");
                    break;
 
                case 3:
                    Console.WriteLine("You Joined on a Tuesday");
                    break;
 
                case 4:
                    Console.WriteLine("You Joined on a Wednesday");
                    break;
 
                case 5:
                    Console.WriteLine("You Joined on a Thursday");
                    break;
 
                case 6:
                    Console.WriteLine("You Joined on a Friday");
                    break;
 
                case 7:
                    Console.WriteLine("You Joined on a Saturday");
                    break;
            }
 
            int ResigDay;
            Console.WriteLine("Enter the Resignation Date:");
            ResigDay = Convert.ToInt32(Console.ReadLine());
 
            switch (ResigDay)
            {
                case 1:
                    Console.WriteLine("You Resigned on a Sunday");
                    break;
 
                case 2:
                    Console.WriteLine("You Resigned on a Monday");
                    break;
 
                case 3:
                    Console.WriteLine("You Resigned on a Tuesday");
                    break;
 
                case 4:
                    Console.WriteLine("You Resigned on a Wednesday");
                    break;
 
                case 5:
                    Console.WriteLine("You Resigned on a Thursday");
                    break;
 
                case 6:
                    Console.WriteLine("You Resigned on a Friday");
                    break;
 
                case 7:
                    Console.WriteLine("You Resigned on a Saturday");
                    break;
            }
 
 
            Console.ReadLine();
 
        }
    }
}

This program displays the weekday of joining and resigning based on the day code entered by the user. While, there are no errors in the code, there is a problem – repetition of code. The switch block in the second case (Resignation Day) is more or less the same except for the prefix to the output message being You Resigned on a . Looping is meant to minimize code repetition, but it is not applicable everywhere. In scenarios such as these we should use functions to reduce code repetition. Below is the same program when done by using a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int JoinDay;
 
            Console.WriteLine("Enter the day of Joining:");
            JoinDay = Convert.ToInt32(Console.ReadLine());
 
            Console.WriteLine("You Joined on a {0}", GetDayFromCode(JoinDay));
 
            int ResigDay;
            Console.WriteLine("Enter the Resignation Date:");
            ResigDay = Convert.ToInt32(Console.ReadLine());
 
            Console.WriteLine("You Resigned on a {0}", GetDayFromCode(ResigDay));
 
            Console.ReadLine();
 
        }
 
        public static string GetDayFromCode(int Code)
        {
            switch (Code)
            {
                case 1:
                    return "Sunday";
 
                case 2:
                    return "Monday";
 
                case 3:
                    return "Tuesday";
 
                case 4:
                    return "Wednesday";
 
                case 5:
                    return "Thursday";
 
                case 6:
                    return "Friday";
 
                case 7:
                    return "Saturday";
 
                default:
                    return "";
            }
 
        }
    }
}

We have saved 28 lines by using the function for just 2 cases – Date of Joining & Resigning.

Note: – We haven’t added provision for handling invalid day codes i.e values not belonging to the range 1 – 7.

The terms function and methods are used interchangeably. Functions are composed of statements that are grouped under a name and can be used repeatedly by just calling the function.

Declaration

Before we can use a function, we need to define its properties, what it does and the value that it returns. Any function declaration has two parts – Signature and Body. We will use this function as our example to study the two parts.

1
2
3
4
5
public int SumOfTwoNumbers(int Num1, int Num2)
{
    int Sum = Num1 + Num2;
    return Sum;
}
Function Signature

The function signature is composed of the Return Type, Function Name and the optional Parameters and Access Specifier.

  • Return Type
    The return type determines the type of value that the function will return. It can be any of the atomic data types (int, char, string, bool, float, etc) or the user defined types (enums, objects, structures). A function that does not return any value should have a return type of void.
  • Function Name
    The function name can be anything that follows the naming rules:-

    • The name must begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
    • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the function name.
    • A function name must not be the same as a reserved keyword such as using, public, etc.
    • The name can contain any number of the allowed characters.
    • Functions with the same class cannot have the same name
  • Parameters
    Functions take values as input, process it and return the output. These inputs are in the form of parameters. The parameters themselves are composed of the data type and the parameter name. The data type restricts the values that can be passed to the function (int only allows Integer values, bool allows Boolean values and so on) and the parameter name can be used like a regular variable under the function body. This variable would be initialized with the value that is passed to the function when it is invoked (called). A function can have any number of parameters each of which need to separated by a comma.
Function Body

This is where we define what the function actually does. In our case, the body is composed of the lineint Sum = Num1 + Num2; which does the actual calculation and return Sum which returns the value to the calling function. Every function (except the constructor and destructor) which doesn’t have a return type of void must return a value. The return value must comply with the data type specified in the signature.

Calling/Invoking the function

By calling/invoking the function, we imply using it – which results in the lines of code written inside it being executed. Calling a function is very simple. We do so by the following syntax:-

FunctionName(param1, param2 …);

In our case, it would go something like – SumOfTwoNumbers(6, 9);. This line will pass the execution to the function SumOfTwoNumbers along with the values 6 and 9 which will get copied in the variables Num1 and Num2. After this, the line int Sum = Num1 + Num2; will be executed and the sum of the two numbers will be stored in the variable Sum. Finally, this value will be returned to the calling function, which basically discards this value (as of now). We can store this result as int MySum = SumOfTwoNumbers(6, 9); or display it on screen as follows Console.WriteLine(SumOfTwoNumbers(6, 9));.

Special Cases

A parameter can have two variations – ref and out. When these prefixes are applied to any parameter, its behaviour changes. Normally, the values passed to the function are just copies of the original value and any changes made to this value have no effect on the original value. By using the ref keyword we can force the value to be passed by reference. This creates an alias of the variable which might have a different name but points to the same address in the memory. Thus, changes made to this value reflect in the original value.

The swap function is a trivial example of this difference:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int A = 10, B = 20;
            Console.WriteLine("The value of A = {0} and B = {1}", A, B);
            Swap(A, B);
            Console.WriteLine("The value (after swapping) of A = {0} and B = {1}", A, B);
            Console.ReadLine();
        }
 
        public static void Swap(int A, int B)
        {
            int Temp = A;
            A = B;
            B = Temp;
            Console.WriteLine("The value (during swapping) of A = {0} and B = {1}", A, B);
        }
    }
}

The output of the following program would be:-

The value of A = 10 and B = 20
The value (during swapping) of A = 20 and B = 10
The value (after swapping) of A = 10 and B = 20

As you can see, the changes made to the value of A and B inside the Swap function have no effect on the values of A and B inside the Main function. This is because both pairs of variable belong to their scopes (the Swap function and the Main Function) and are hence separate. However, by using the ref keyword, we can point the variable A inside the Main and Swap function to the same memory location (same holds for the variable B). The variable A inside the Swap function will be called an alias of the variable A inside the Main function. The alias doesn’t need to have the same name either. The alias stores the memory address of the original variable and not its value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int A = 10, B = 20;
            Console.WriteLine("The value of A = {0} and B = {1}", A, B);
            Swap(ref A, ref B);
            Console.WriteLine("The value (after swapping) of A = {0} and B = {1}", A, B);
            Console.ReadLine();
        }
 
        public static void Swap(ref int A, ref int B)
        {
            int Temp = A;
            A = B;
            B = Temp;
            Console.WriteLine("The value (during swapping) of A = {0} and B = {1}", A, B);
        }
    }
}

Output:-

The value of A = 10 and B = 20
The value (during swapping) of A = 20 and B = 10
The value (after swapping) of A = 20 and B = 10

By using the ref keyword, we have made the change persistent inside the Main function.

Note: It is necessary to specify the ref keyword during function calling.

A function can take multiple inputs but only return a single value. There might be situations when we need multiple values as output from the function. We can do this by using either the ref or the out keyword. Both of them result in references being passed. The only difference is that the out keyword passes along null values and is hence ideally suited for output purposes.

Note: It is necessary to specify the out keyword during function calling.

C#

C# Tutorial : Lesson 07 – Creating Value Types & Reference Types – Part II

July 23rd, 2007
foreach statement

This statement is explicitly used to traverse through arrays. The benefit of using foreach over the normal for statement is that it is not necessary to check the size of the array while using the former.

Syntax:-

foreach(type identifier in expression)
{
statement 1;
statement 2;

}

Suppose we have an array StudentNames containing the name of all the students in a class. We need to display the name of each one of them on screen. First we will see how it can be done using the for loop.

1
2
3
4
5
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
for (int I = 0; I < StudentNames.Length; I  )
{
	Console.WriteLine(StudentNames[I]);
}

Now we’ll use the foreach statement to do this.

1
2
3
4
5
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
foreach (string StudentName in StudentNames)
{
	Console.WriteLine(StudentName);
}
Param Arrays

Remember the Console.WriteLine method which outputs the result using a string format followed by the additional values as input parameters. For example: Console.WriteLine(“The sum of {0} and {1} is {2}”, Num1, Num2, Num1 Num2); would display The sum of 5 and 6 is 11 for values 5 and 6 for Num1 and Num2 respectively. What is worth noting here, is that WriteLine() can take any number of parameters after the string format. So, something like this would work as well:-

Console.WriteLine("The Prime Numbers -> {0}, {1}, {2}, {3}, {4}", 2, 3, 5, 7, 11);

This is done by the param array data type. Example:-

1
2
3
4
5
6
7
8
9
public static int Sum(params int[] Numbers)
{
	int Sum = 0;
	foreach (int Number in Numbers)
	{
		Sum  = Number;
	}
	return Sum;
}

This is a function to return the sum of any number of numbers. The numbers to be summed are passed as parameters during the function call as: Sum(4, 69, 13, 99);

Note: param array should be the last parameter in the function signature which also means that only one param array can be used in a function. Why is this done? Consider the following function signature: public static int MyFunction(params int[] A, int C). How would we call the function if this were to be allowed? MyFunction(1, 2, 3, 4, 5); How can the compiler determine where the values for the param array A finish? Actually, if a reverse scanning of parameters were to be done, this could be determined. But that would increase useless complexity of having to implement this along with the normal forward scanning of parameters.

Multi Dimensional Arrays

Up until now, we have only worked with Single Dimensional arrays. Now we shall see how the Multi Dimensional arrays are declared, initialized and manipulated. The pictures below show how the Single and Double Dimensional arrays are represented.

Single Dimensional Array

Multi Dimensional Array

While, the Single Dimensional arrays are represented as a single row of elements, Double Dimensional arrays are represented by multiple rows. Similarly, arrays with 3 dimensions would be represented in 3D space along the three axes.

Declaration

Declaration is done by the syntax:-

datatype [ , ] VariableName;

The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.

Example Usage:-

int [ , ] Numbers;
Initialization

Initialization is done in a way where each row is treated like a single dimensional array. Example:-

1
2
3
4
5
6
int[,] Numbers = new int[3, 3]
{
	{1, 2, 3},
	{4, 5, 6},
	{7, 8, 9}
};
Assigning Values

Values can be assigned as:-

Numbers[1, 2] = 7;
Array Class

The Array class defined in the System namespace serves as the base class for all the arrays in the Common Language Runtime. It can be used to create, manipulate, search and sort arrays.

Some of the common Properties and methods are summarized below.

Properties

  • IsFixedSize – Returns a boolean value (True / False) indicating whether the array is of Fixed Size or not.
  • IsReadOnly – Returns a boolean value (True / False) indicating whether the array is Read Only or not.
  • Length – Returns a 32-bit integer that represents the total number of elements across all dimensions in the array.
  • Rank – Returns the number of dimensions (also called the Rank) of the array.
Methods
  • BinarySearch – Performs the faster Binary Search algorithm on the array and returns the number if found.
  • Clear – Resets the value of the supplied range of elements in the array to the default values of the datatype:-
    • int – 0
    • bool – false
    • Reference Data Types – Null
  • Copy – Copies a range of elements to another array along with type casting and boxing as required
  • CopTo – Copies all elements to the specified single dimensional array
  • Find – Searches for the given value and returns its first occurrence in the array
  • FindAll – Returns all occurrences of the searched element in the array
  • GetLength – Returns the 32 bit length of the array
  • GetValue – Returns the value of the specified item in the array
  • IndexOf – Searches for the given value and returns the index of the first position its found in
  • Resize – Resizes the array
  • Reverse – Reverses the order of the elements. (Works only on a single dimensional array)
  • SetValue – Sets the value at the specified location of the array
  • Sort – Sorts the elements. (Works only on a single dimensional array)
Collections

An integer array can only store integers. Same goes for any other array type – string, boolean, etc. Collections overcome this limitation of arrays and can store elements of different types as items. This is possible because Collections actually store references and not values. We use the System.Collections namespace to work with collections.

Boxing – No, not the Sport! Boxing is the automatic conversion of value types to reference types allowing them to be stored in collections.
Unboxing – The reverse of the former, conversion of reference type to value type.

Because Collections store references, it is necessary to do the above conversions while storing and retrieving values in Collections.

Array List – Array List is a better alternative to arrays because of the following advantages it offers over arrays. It resides in the System.Collection namespace.

  • Resizing – Arrays cannot be resized natively. So, one has to create a new array and copy the elements of the existing one followed by rearrangement of references for this process. Array List on the other hand work on the concept of Linked List where memory is allocated and deallocated at runtime as and when required.
  • Adding an element – To add an element we need to first create a new array, copy the values before the position where the new element is to be inserted, insert the new element and then insert the remaining elements. Again, a cumbersome process for arrays. Array Lists only need to allocate memory for the new element and resolve the references of the elements on both side of the new element.
  • Deleting an element – All elements after the element to be deleted need to be shifted forward to fill up the vacancy created by the deletion. Array Lists rely on releasing the memory occupied by the element and resolving the references of the elements on both sides.

Common Methods used by the Array List class:-

  • Add – Adds an item at the end of the Array List
  • Clear – Removes all the items from the Array List
  • Insert – Inserts an element into the Array List at the specified position
  • Reverse – Reverses the order of all the elements or a portion of the Array List
  • Remove – Deletes the item at its first occurrence
  • TrimToSize – Sets the maximum capacity to the number of elements currently in the the Array List

Other Classes that the collection namespace provides are:-

  • Queue – A Collection that works on the First-In-First-Out (FIFO) rule. Here, insertion of elements occur at the rear and deletion at the front.
  • Stack – Works on the Last-In-First-Out (LIFO) rule. Both insertion and deletion occur at the top of the stack.
  • Hash Table – It uses unique keys to access/store elements in the collection.

C#

C# Tutorial : Lesson 06 – Creating Value Types & Reference Types – Part I

July 23rd, 2007
Value Types & Reference Types

In C#, Variables are either value types or reference types depending on what they store, values or references. By reference we imply that the variable holds the memory address of another location where the actual value is stored. All built in data types – Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The following is a diagrammatic representation of these two types.

In this picture there are two variables Num1 and Num2. Both of these being integer variables store the values directly.

The two variables in this case are actually objects of a car class. As you can see, they do not store the values directly but only a pointer to the memory location where the value is actually stored.

Consider the following code snippet:-

1
2
3
4
5
6
int Num1, Num2;
Num1 = 100;
Num2 = Num1;
Num1 ++;
Console.WriteLine("Num1={0}", Num1);
Console.WriteLine("Num2={0}", Num2);

Here we declare two integer variables, Num1 and Num2. On line 2 we set the value of Num1 to 100 and at line 3, we copy the value of Num1 to Num2. Both Num1 and Num2 now store 100. In the next line, we increment the value of Num1 by 1, thus it stores 101 now. This doesn’t make any change in the value of Num2 as both of them are value types and have a separate storage location in the memory. Finally, we display the numbers and the output comes as:-

Num1=101
Num2=100

Now take a look at this code snippet:-

1
2
3
4
5
6
Car Ferrari, McLaren;
Ferrari = new Car("F2004");
McLaren = Ferrari;
McLaren.Model = "F2002";
Console.WriteLine("Ferrari={0}", Ferrari.Model);
Console.WriteLine("McLaren={0}", McLaren.Model);

Two objects of the Car class are declared. We instantiate Ferrari by using the new keyword, passing the value F2004 to its constructor which sets the Model to F2004. The third line McLaren = Ferrari; copies the value stored by the object Ferrari to McLaren. All classes being reference types, the objects store the memory address of the actual storage location. Hence, by copying Ferrari to McLaren, we are actually copying the memory location. Now both Ferrari & McLaren are pointing to the same physical location in the memory. In the next line, the model for the McLaren is changed to F2002. This doesn’t make any change to the value stored by the McLaren object, i.e the memory address. The change occurs in the storage location pointed to by the McLaren object. Since, Ferrari is pointing to the same memory location this change reflects there as well and the results of the last two lines are:-

Ferrari=F2002
McLaren=F2002

Structures

A structure is a value data type which is used to group related heterogeneous data types. Say you want to store the details of all the employees of your company such as – Name, Post, Salary, Joining Date, etc. In such a scenario we can create a structure named employee which would be composed of these fields. We use the struct keyword to create structures with the following syntax:-

struct StructureName
{
member variable 1
member variable 2

}

Structures are similar to classes in the sense that they contain data members and functions, have access specifiers and need to be instantiated, but they do have notable differences such as:-

  • Structures are value types whereas classes are reference types
  • Structures can not be inherited
  • They cannot have default constructor

Example Usage:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Employee
{
	public string Name;
	public string Post;
	public int Salary;
	public string JoiningDate;
}
static void Main(string[] args)
{
	Employee Emp1 = new Employee();
	Console.WriteLine("Enter Employee's Name");
	Emp1.Name = Console.ReadLine();
	Console.WriteLine("Enter Employee's Post");
	Emp1.Post = Console.ReadLine();
	Console.WriteLine("Enter Employee's Salary");
	Emp1.Salary = Console.ReadLine();
	Console.WriteLine("Enter Employee's Joining Date");
	Emp1.JoiningDate = Console.ReadLine();
}

Note: Unlike in other languages such as C/C , structures in C# can have member functions.

Enumeration

Enumeration is another value data type that we use to store non generic values such as the name of the day – Sunday, Monday, etc. One may question the need for enumeration considering that we can use the string data type to store the names. But, one could assign just about any value to the day, which we certainly don’t want. We could also use the numbers from 0 – 6 to denote the 7 days. However, that doesn’t clarify whether 0 is for Sunday or Saturday. The enum keyword is used to create an enumerated data type with the following syntax:-

enum EnumDataType { Value1, Value2, and so on }

Example usage:-

1
2
3
4
5
6
enum Month { Jan, Feb, Mar, Apr, May, Jun, Aug, Sep, Oct, Nov, Dec };
static void Main(string[] args)
{
	Month ThisMonth;
	ThisMonth = Month.May;
}

Note:- The values of an enumerated data type are assigned in design time and not at runtime using the Console.Read or Console.ReadLine method.

Arrays

An array is a collection of values of the same data type, grouped under the same name and referred to by their distinct indexes. This is how they are represented in the memory.

Declaration

Syntax:-

datatype[] ArrayName;

  • Where datatype is the type of data that the array will store – int, string, char, etc.
  • [] Specifies the size of the array.
  • ArrayName is the name with which we would be using the array.
  • Example usage:-

    int[] Marks;

    Initialization
    Memory is allocated to the array only when it is instantiated. The instantiation can be done in the following methods. Once initialized a default value is assigned to all of the elements depending on their data type – 0 for int, “” (NULL String) for char or string, etc.

    Syntax:-

    ArrayName = new datatype[size];

    This step can be done along with the declaration.

    datatype[] ArrayName = new datatype[size];

    Example Usage:-

    int[] Marks = new int[10];

    Note: This creates 10 elements starting from 0 to 9

    Assigning values
    Each element of the array can be accessed by specifying their index along with the ArrayName.

    ArrayName[index] = value;

    Example:-

    Marks[5] = 99;

    Values can also be assigned during declaration as follows:-

    datatype[] ArrayName = {value1, value2, value3 and so on};

    Example:-

    int[] Marks = {100, 13, 69, 99};

    Using this process implicitly sets the size for the array. In this case it would be 4. The elements can be accessed by their indexes starting from 0 to 3. Note: In C# Index always starts at 0.

    Using the following is equivalent to using the above line of code.

    int[] Marks = int[4] {100, 13, 69, 99};

    Copying an Array
    You can copy an array just as easily you copy other variables. Example:-

    1
    2
    
    int[] Source = {0, 1 , 2, 3, 4};
    int[]Destination = Source;

    One point to note is that an array being a reference type, both these arrays point to the same location in memory and any change made in either of them would be reflected in the other one as well. To make separate copies of the array, we need to copy each of the elements individually. The code below does just that.

    1
    2
    3
    4
    5
    6
    
    int[] Source = { 0, 1, 2, 3 };
    int[] Destination = new int[Source.Length]; // Set the size of the destination to be the same as that of the source
    for (int I = 0; I < Source.Length; I  )
    {
    	Destination[I] = Source[I];
    }

    This step can be done along with the declaration.

    datatype[] ArrayName = new datatype[size];

    Example Usage:-

    int[] Marks = new int[10];

    Note: This creates 10 elements starting from 0 to 9

    C#

FileZilla – Open Source FTP Client

July 19th, 2007

FileZillaNo matter what the critics say, FTP still is the best way to transfer your web pages and associated files to the server. FileZilla is an open source, simple, quick and reliable FTP client that packs in a lot of features. The software targeted at the 32 bit Microsoft Windows platforms, is licensed under the GNU General Public License. All in all, a must have for all the site administrators out there.

Here’s a listing of some of it’s features.

  • FTP & SFTP Protocol support
  • Site Manager to store connection & initialization details
  • Support for Proxy
  • Multi-threaded download/upload
  • ASCII/Binary/Auto Transfer Modes
  • Download/Upload En-queuing

Links:-

Source Forge Project

Freeware

Venturing into the World of Game Programming

July 18th, 2007

Yesterday, I found an excellent article on how to begin Game Programming using the DirectX API. The tutorials are based on the CLR brothers C# and VB .NET. I would recommend going along with C# because the tutorials are not 100% VB .NET tested.

Since then, I have had to download the Direct X SDK and re-format my Windows partition. Thanks to the power failure attributing to Visual Studio Orcas Uninstallation going berserk. That wasn’t the end of it though. The old nLited Unattended CD of Windows XP SP2 which was backed up on the CD-RW blew as well.

Back to the tutorials! The entire article being well explained is divided into 8 parts. I’ve managed to sail through the first two. Although, I cannot say that everything was crystal clear. This whole venture requires a lot of background learning on the basis of the co-ordinate system and patience is the key.

Here goes the link.

General

Creating a Custom Skinned Form in .NET

June 7th, 2007

Making handsome applications is a top priority for eye candy lovers as myself. Thanks to the Windows Forms introduced in .NET, VB programmers no longer needed to scratch their heads over manifest files, inconsistencies in the runtime and design time look of their applications.

Again, the urge to build applications that stand out has pushed the demand for custom skinning of Forms. Fortunately, implementing these using .NET are much easier, although still no child’s play. The complicacies involved in the Drawing of Windows is something that I am realizing now. Countless Messages need to be intercepted, scenarios handled. I must say that there are quite a few quality products that allow painless skinning of Forms and controls, Skincrafter being one of them.

Though, what I want is to have total control over the skinning. Something which can only come when the source code is with you. After a lot of Googling, I found a project developed by Szymon Kobalczyk to be extremely good. But once again, I am not satisfied with things. I want to create a skinning tool that would be even better and so I start a journey today, as I did with Pika Bot. Only this time, with a lot more experience.

I have been traversing through Szymon’s codes quite a lot. Getting a hold of someone’s code takes a lot of time. But I do seem to be getting there little by little. I am going to build the skinner from ground up and use his codes for references where I falter.

Friday, June 8 2007

Not much luck in getting the thing to work. Nor have I been able to rectify the resizing bug that’s present in Szymon’s code.

Sunday, June 10 2007

I have made considerable progress in the Skinner. Most of the messages have been intercepted pretty well although some bugs continue to exist along with an overall slowness in the drawing.

Saturday, June 16 2007

Fixed major problems which had quite simple roots. Still, a few painting bugs remain.

Saturday, June 23 2007

The Form Skinner is almost ready to be released. It also includes a new licensing mechanism that uses hardware fingerprints for activation.

General

C# Tutorial : Lesson 05 – Encapsulation & Abstraction

April 9th, 2007
Encapsulation & Abstraction

Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.

Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).

Consider the example from the programmer’s perspective who wants to allow the user to add items to a list. The user only needs to click a button to add an item (Abstraction). The mechanism of how the item is added to the list is not essential for him (Encapsulation).

Below is a graphical representation of Encapsulation for the car class.

Implementing Encapsulation & Abstraction

Consider the countless advertisements being bombarded to viewers. The viewer does not listen to each one of them, rather only those he?s curious about. We use access specifiers to restrict the scope (visibility) of the class members.

Types of Access Specifiers
  • public – The members (Functions & Variables) declared as public can be accessed from anywhere.
  • private – Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;
  • protected – Protected members can be accessed only from the child classes.
  • internal – Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.

    Both these classes are equivalent.

    1
    2
    3
    4
    
    class MyClass
    {
     
    }
    1
    2
    3
    4
    
    internal class MyClass
    {
     
    }
  • protected internal – Similar to protected, protected internal members can be accessed from the child classes but only within the application.

Note: The members are always accessible to its own member functions, irrespective of the access specifier.

Lets see an example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class House
{
	// Data Members
	public string DrawingRoom;
	private string Kitchen;
 
	// Member Functions
	private bool EnterDrawingRoom()
	{
		DrawingRoom = "The Drawing Room";
	}
 
	public bool EnterKitchen()
	{
		Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function
		can modify it because the member function itself has access to all other members. */
	}
 
}
 
class MainClass
{
	public static void Main()
	{
		House TheBlackHouse = new House();
		TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible
		from outside the class */
		TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible
		 from outside the class. */
		TheBlackHouse.EnterDrawingRoom(); /* Error - Private Member Function is not accessible
		// from outside the class. */
		TheBlackHouse.EnterKitchen(); /* OK - Public Data Member is accessible from outside
		the class. */
	}
}

Lets study the code. Inside the main function we declare an object TheBlackHouse of the House class. Thereafter, we set the value of the data member DrawingRoom for TheBlackHouse to “Main Drawing Room”. Since, DrawingRoom is declared as public, the above step works without any error. On the next line, TheBlackHouse.Kitchen = “Main Kitchen”; we are trying to assign the value “Main Kitchen” to the Kitchen variable of TheBlackHouse object. However, Kitchen is declared as private. Hence, this step generates an error.

In the next line, we are trying to call the private method EnterDrawingRoom for the object. This generates an error as well. Finally, we are calling the EnterKitchen function which is declared as public. Notice that inside the EnterKitchen function, we are assigning the value “The Kitchen” to the private variable Kitchen. This does not generate an error because the EnterKitchen method belongs to the same class and it has access to all the members inside the class, irrespective of the access specifier.

Why do we need Encapsulation, Abstraction?

Programming is all about concepts, different from coding where we basically translate the logic to language specific codes. When given a problem statement, there might be a number of ways to solve it. The logic devised to solve it will depend of the programmer. What we must learn to implement is the most efficient approach; efficient in terms of time, memory & cost. Object oriented methodologies such as these are what allow us to maintain efficiency.

By using encapsulation & abstraction, we reduce complexity by ignoring unimportant details and we maintain effectiveness by representing important ones.

C#

C# Tutorial : Lesson 04 – Object Oriented Programming

April 9th, 2007
Object Oriented Programming

Object Oriented Programming is a methodology modeled on real life. It comprises of the basic unit, an object, being used in implementing a program. Think of all the objects around you – cars, buses, birds, trees, etc. You will find countless ones of them, everywhere you go. In order to tackle this huge number, we started classifying them, thus came the term Class.

Class

A class is a composition of the theoretic characteristics (attributes and properties) of an object and the things it can do – behaviors, methods and features. Take the Car as an example. Its characteristics can include speed, color, number of gears, etc and it exhibits behaviors such as accelerate, brake and gear-change.

Object

An object is an instance of a class. Consider the Car class above, the Aston Martin that was used in the movie – Die another Day is an object of the car class. One point to note is that each object has at least one attribute that makes it unique.

Message Passing

Objects do not exist in isolation. They interact with other objects. These interactions take place through messages. Message passing is the process by which an object (sender) sends data to another object (receiver) or asks the other object to invoke a method. Thus, each message has a sender and a receiver.

Behavior

It is how an object acts and reacts, in terms of its state changes and message passing. For example, when the driver applies the break, the car comes to a stop.

This was all about the object oriented methodology. Now, let us take a look on how OOP is used in C#

Declaring Classes

We declare classes using the following syntax:-

class < Class Name >
{

data members…

member functions…

}

Here class is a keyword. Class name can be anything that follows the naming rules.

Rules for naming classes
  • A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.
  • A class name must not be the same as a reserved keyword such as using, public, etc.

Conventions for naming classes

  • Class Name must be meaningful, ideally a noun.
  • Naming of classes can be done using either the Pascal case, where the first character is capital and the rest are in small letters or using the Camel Case in which the first letter is in small case but the first letter of each successive word is in caps. Example:-
    • Pascal Case: Classone
    • Camel Case: classOne

The conventions are not mandatory but best practices, abiding by which allows others to easily understand our code.

Data members are the variables or other objects declared inside the class while member functions are the functions declared in it.

Example Class:-

class Student
{
	// Data Members
	public string Name;
	public int Age;
 
	// Member Function
	public void Display()
	{
		Console.WriteLine("Name {0}\n Age {1}", Name, Age);
	}
}

The public access specifier has been used in order to allow the data members & functions to be visible from outside the class. The access specifiers will be explained in the forthcoming tutorials.

Declaring & Instantiating Objects

Creating objects is similar to declaring variables and can be done using the syntax:-

<Class Name> <Object Name>;

Example: Student S1;

Before we start using the object, we need to instantiate it. Instantiation involves memory allocation and other basic initializations contained in the object’s constructor. We use the new keyword to instantiate objects. The syntax for which is given below:-

Note: Constructor is a special member function of a class that is used to initialize the data members. It will be dealt with, in later tutorials.

<Object Name> = new <Class Name>;

Example Usage: S1 = new Student();

These two steps can be done in a single line of code as Student S1 = new Student();

Using the Objects

We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();

Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;

Releasing Memory

To release the memory occupied by the object we use S1 = null;

Example Program:-

using System;
 
namespace CSTutorials
{
	class Student
	{
		// Data Members
		public string Name;
		public int Age;
 
		// Member Function
		public void Display()
		{
			Console.WriteLine("Name {0}\n Age {1}", Name, Age);
		}
	}
 
	class Program
	{
		static void Main(string[] args)
		{
			Student S1;			 // Declaration
			S1 = new Student();	 // Instantiation
 
			Student S2 = new Student();	 // Single line Declaration &amp; Instantiation
 
			// Assigning value to member variables
			S1.Name = "Michael";
			S1.Age = 37;
 
			S2.Name = "Kimi";
			S2.Age = 25;
 
			// Invoking member function
			S1.Display();
			S2.Display();
			Console.ReadLine();
		}
	}
 
}
Benefits of Object Oriented Programming
  • Realistic Modeling: Living in a ‘World of Objects’, the model built on real life is a much better approach because it allows issues to be tackled with greater accuracy.
  • Re-usability of code: Think of a scenario where a car making company specialized in two seater’s decides to launch a four seater model. Converting the two seater model to a four seater is easier than designing a new model altogether.
  • Resilience to change: Being compartmentalized, individual objects can be improved without having to re-package the entire software.
  • Polymorphism: The behavior of an object can depend upon the state its in, thus exhibiting Polymorphism. Consider a car colliding with a wall. The impact of the process would depend upon the approach speed of the car, the Angle it strikes in, the strength of the wall and so on. If two cars were to collide, the results would be much different, with both of them receiving considerable damage.

C#

C# Tutorial : Lesson 03 – Programming Constructs

April 9th, 2007
Conditional Branching

By branching we imply, having different paths for execution. Conditions are used to determine which statements need to be executed. Suppose, you have a program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.

C# provides the following conditional constructs:-

if .. else

Syntax:-
if (<condition>)
{
statements
}
else
{
statements
}

The else part is optional and can be omitted. The working of if .. else construct is very simple and follows the pattern – If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, the execution flow continues to the proceeding statements.

Here’s an example:-

1
2
3
4
5
6
7
8
9
10
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 – Console.WriteLine(“You are not permitted in here.”); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed.

The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:-

1
2
3
4
5
6
7
8
9
10
11
12
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian == false))
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

At line 4 the user’s response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian == false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message – You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message – You may come in will be displayed.

A number of conditions can be chained by using else if as follows:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
	Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
	Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
	Console.WriteLine("Welcome Programmer");
}
else
{
	Console.WriteLine("Welcome dear Customer");
}

In this case, if the salary supplied by the user is greater than 250000, the message – Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message – Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.

switch .. case Construct

Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.

Syntax:-
switch (<expression>)
{
case Expression_1;
statements
break;

case Expression_2;
statements
break;

}

break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.

Example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
	case 1:
		Console.WriteLine("January");
		break;
 
	case 2:
		Console.WriteLine("February");
		break;
 
	case 3:
		Console.WriteLine("March");
		break;
 
	case 4:
		Console.WriteLine("April");
		break;
 
	case 5:
		Console.WriteLine("May");
		break;
 
	case 6:
		Console.WriteLine("June");
		break;
 
	case 7:
		Console.WriteLine("July");
		break;
 
	case 8:
		Console.WriteLine("August");
		break;
 
	case 9:
		Console.WriteLine("September");
		break;
 
	case 10:
		Console.WriteLine("October");
		break;
 
	case 11:
		Console.WriteLine("November");
		break;
 
	case 12:
		Console.WriteLine("December");
		break;
 
	default:
		Console.WriteLine("There are only 12 Months.");
		break;
}

Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months. will be displayed.

Multiple Values can be made to lead to the same block of statements by excluding the break statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Console.WriteLine("Enter a number  (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
	case 2:
	case 3:
	case 5:
	case 7:
		Console.WriteLine("The number is prime.");
		break;
	case 1:
	case 9:
		Console.WriteLine("The number is odd.");
		break;
	case 4:
	case 6:
	case 8:
		Console.WriteLine("The number is Even");
		break;
	default:
		Console.WriteLine("The number is not in range.");
		break;
}
Looping

A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 – 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 – 1000? Using the computer’s iterative power is a much better approach.

C# supports 3 kinds of loops which are discussed below:-

The for loop

This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-

for(<initialization>;<condition>;<increment/decrement>)
{
statements
}

To print numbers within a range, say 1 – 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.

1
2
3
4
for(int I = 1; I <= 1000; I  )
{
	Console.WriteLine(I);
}

Lets break the for statement down:-
Initialization: int I = 1
Condition: I <= 1000
Increment: I

All the parts here are optional and can be left out. So, you can initialize the variable I, above the for statement and leave out the initialization block. The code would look like this (; I <= 1000; I ). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).

Another variation of a for statement is the empty loop which does not contain any body:-

for(int I = 1; I <= 1000; I++);

Such a for statement is followed by the semicolon.

The while loop

The for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the while statement.

Syntax:-
while(<condition>)
{
statements
}

We don’t have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.

1
2
3
4
5
6
7
8
9
bool Continue = true;
while(Continue == true)
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}

We have declared a boolean variable Continue which we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user’s choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the while loop would keep on executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 – 1000 using while.

1
2
3
4
5
6
int I = 1;
while(I <= 1000)
{
	Console.WriteLine(I);
	I++;
}
The do while loop

The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable continue stores the user’s choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.

1
2
3
4
5
6
7
8
9
10
bool Continue;
do
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);

Note: The while part in the do while loop needs to be terminated with the semicolon.

Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

C#