The .net Base Class Library (BCL) is one of the most comprehensive libraries available at your disposal to start creating applications. The BCL is a huge mass of pre-written code that you can easily incorporate and use in your applications. It contains classes with methods, which allow you to do most of the commonly used tasks. Most of the functionalities that a programmer might think of as being part of a language have been moved to the framework classes. For example, consider that you want to calculate the square root of a number. A function for calculating a square root is no longer available in C#. Instead, you will have to use the System.Math.Sqrt method from the Base Class Library.
However, note that the Base Class Library is shared among all .net supported languages. To find the square root of a number, Visual Basic, Ada and even COBOL will use the same base class function. This facility makes base class functionality highly consistent across al .net-supported languages as they all will call the square root function in a similar way.
Classes in the Base Class Library are categorized into namespaces based on their functionality. These namespaces have been compiled and packed into Assemblies. Assemblies will be discussed in detail in the future post. As for now think of an assembly as a .DLL file with all the namespaces, classes and methods packaged inside it.
The most commonly used namespaces have been listed out in below Table. This table also lists out the assembly that contains the namespace.
Namespace |
Assembly |
What it contains? |
System |
Mscorlib.dll, System.Net.dll |
Much of the functionality of the BCL is contained within this namespace. Contains various other namespaces within it, some of them are listed below. |
System.Array |
Mscorlib.dll |
Contains classes for manipulating arrays. |
System.Threading |
Mscorlib.dll, System.dll |
Contains classes for Multi-Threading |
System.Math |
Mscorlib.dll |
Contains classes for performing mathematical functions |
System.IO |
Mscorlib.dll, System.IO.dll |
Contains classes for reading and writing to files and streams |
System.Reflection |
Mscorlib.dll |
Contains classes for reading metadata from assemblies |
System.Net |
System.Net.dll |
Contains classes for Internet access and socket programming |
The .net Framework SDK provides you with a tool called WinCV. This tool is used to peek into the assemblies and see what classes are available within them.
We shall now discuss some of the important base class libraries. Let us begin with System.Array.
1. The System.Array Namespace
The System.Array namespace provides us with classes and methods for manipulating arrays. We have learnt how to create and assign elements to arrays in previous sessions. Let us try to recollect how to create an array in C#.
The syntax for declaring an array is:
DataType[] identifier;
So if we want an array of type int, which can hold say 7 elements, we would write
int[] MyArray = {1,2,3,4,5,6,7};
Consider Example 13.
Example 13:
The output of Example 13 will be:
Contents of Array before sorting:
6
4
7
3
5
1
2
Contents of Array after sorting:
1
2
3
4
5
6
7
- In Example 13 we have declared and initialized an array called MyArray with 7 numbers (from 1 to 7 in random order).
- We have then displayed the contents of this array as they are. Note the “\n” in the Console.WriteLine() method. It has been used to enforce a new line. It is known as an Escape Sequence.
- We sort the array using the Sort() method of the Array class. This class is present in the System namespace.
The syntax for the Sort() method is:
Array.Sort(ArrayToSort);
Where ArrayToSort is the name of the array to be sorted. Also you need to ensure that the System namespace has been imported using the using keyword else you need to prefix the syntax with System and the dot operator. The Array.Sort() method does not return any values.
- We finally display the contents of the array after sorting the array using the method of the base class.
Also, if you notice, we have defined a new method called DispMe(). This method takes in one parameter, an array, and iterates through all of its elements displaying them with each pass. We have made use of the DispMe() method twice in the Main() method to display the contents of the array.
Let us try out one more example where we will look for a particular array element and return its position in the array.
Consider Example 14.
Example 14:
Note that in Example 14 we have used the same array (MyArray) as in Example 13 with the same elements.
- We first ask the user to enter a number between 1 and 7.
- We accept this number using the Console.ReadLine() method.
- But Console.ReadLine() returns a string, while we require an integer. To extract the int value from the string that the user has entered we use the ToInt16() method of the Convert class (The Convert class belongs to the System namespace).
- The ToInt16() method converts the parameter to type short (short is the C# alias for System.Int16 struct).
- We then search the array for the occurrence of the number the user has entered. To do this we use the Array.IndexOf() method. This method takes in two parameters, the first one being the array to search and the second being the number to search for. The Array.IndexOf() method returns the location of the number, entered by the user in the array.
The syntax for the Array.IndexOf() method is:
returnVar = Array.IndexOf(ArrayToSearch, WhatToSearch)
Here returnVar is the return type
ArrayToSearch is the Array that needs to be searched
WhatToSearch is the element that needs to be searched for in the array
- Finally we display the location at which the number was found to the user.
There are two things of importance that you will learn from this example. Firstly, you must understand that C# is type safe, it checks for unsafe casts very strictly and will not allow you to type cast one variable type to another, which might result in data loss. Note that Console.ReadLine() returns a string, while we need an int value to search the array. This is the reason we must use the Convert.ToInt16() method to convert the string to an int.
Secondly, you know how to search an array for the occurrence of an element using the System.Array base class.
Other notable methods of the System.Array class along with what they do are listed below.
Method |
Syntax |
Does this… |
Clear |
void Array.Clear(ArrayName); |
Clears (deletes) the elements of the specified Array. |
Copy |
void Array.Copy(arraySource, arrayDest); |
Copies the elements of one array to another. |
LastIndexOf |
int Array.LastIndexOf(array, searchElement); |
Returns the index of the last occurrence of a value in the Array. |
Reverse |
Void Array.Reverse(arrayName); |
Reverses the order of the elements in an Array. |
2. The System.Threading Namespace
In C# we use the System.Threading namespace to implement multi-threading into our programs. Multi-threading is the concept of running one or more instances (known as threads) of either the same program or parts of the program simultaneously.
Consider Example 15.
Example 15:
The output of Example 15 will be as given below (your output may vary).
1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Let us first understand what we are trying to do in Example 15. The example consists of two methods, one obviously the Main() method and the second is the RunMe() method. What we are trying to do is run two instances of the RunMe() method from Main() at the same time such that they run in parallel. All that RunMe() method does is that it prints the numbers from 1 to 9 to your console.
In Example 15, note the syntax of the code where we create the new thread (instance) of the RunMe() Method.
- First we create an object of the class Thread by specifying the class name
- This is followed by the object name which in this case is Me
- Then we put an equals to (=) sign followed by the new keyword
- This is followed by the class name. The parameters passed to it are the new keyword with the ThreadStart class to which the method to be run is passed. This ends the Thread definition.
In the next line we begin the thread by invoking the Start() method of th Me (which is of type Thread) object. This begins a new thread which runs the RunMe() method and this method runs in parallel to our Main() method.
In the next line, after we start the thread which runs the RunMe() method, we begin the RunMe() method from Main() too. Thus, two instances of the RunMe() method running at the same time. However, since both the methods output to the same console the output seems a little garbled. Since the RunMe() thread began first it might have had started printing the numbers then when the second instance of RunMe() begins from Main() it starts writing to the same console the same numbers due to which the numbers might sometimes be repeated but not in order.
To overcome this problem C# provides you with a Lock mechanism. This lock mechanism is also known as synchronization of threads.
3. Synchronization of Threads
Synchronization of threads means making sure that the different threads co-ordinate their access to shared resource (For example the console). Synchronization, as mentioned earlier, is provided in C# bu the lock keyword. The lock mechanism makes sure that only one thread at a time can access a method or code. The lock mechanism has been implemented in Example 16, which is a modification of Example 15.
Example 16:
The output of Example 16 will be:
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
Note that the numbers displayed on the console (output) are now in order. This is simply because we have locked the RunMe() method. Also note that RunMe() method is no longer static as we need to access it from an instance of the Test class also.
4. The System.IO Namespace
The System.IO Namespace provides us with plenty of classes for file/stream input/output. This namespace also provides us with classes File and Directory, which allow us to operate on files and directories. Operations such as copying, moving, renaming and deleting can easily be done.
Consider Example 17. It lists out the files with the extension .cs in the current directory.
Example 17:
The output of the program depends on the files you have with the .cs extension in the directory you run the program from.
In Example 17, we use the GetFiles() method of the DirectoryInfo class to get all the files with the .cs extension in the current directory.
- In the Main() method we first create an array F of type FileInfo[].
- Next we create an object DI of the class DirectoryInfo (of the System.IO Namespace). Note tha we pass the current directory to its constructor (note that we pass the “.” which stands for the current directory).
- We then fill up the F array with the files with the extension .cs using the GetFiles() method of the DI object.
- Next, using the foreach loop we iterate through all the elements in the array F, and display its contents on the console.
Now we know how to list files in a directory. Let us now take a look at how to create a directory. Consider Example 18.
Example 18:
The output of Example 18 will be:
Creatin' Directory C:\Scooby ...
Directory Created on : 29-Apr-15 11:49:30 AM
In Example 18 we use the Directory.CreateDirectory() method of the System.IO namespace to create a directory. The directory name (with path) needs to be passed as the parameter to the function as seen in the code. If you look carefully, there is an @ symbol prefixed to the string passed. The @ symbol is used to override any escape sequences, which the compiler might get confused with, as we are using the “\” symbol within the string, we are passing.
Next we use the Directory.GetCreationTime() method to get the Directory creation date and time. This method takes in the directory name as the parameter and returns an object of type DateTime.
We finally write the contents of the DateTime object, CreationDate, to the console.
The other notable methods of the Directory class of the System.IO namespace along with what they do are listed below.
Method |
Syntax |
Does this… |
Delete |
void Delete(stringPath); |
Deletes a directory and its contents. |
Exists |
bool Exists(stringPath); |
Checks whether the given path refers to an existing directory. |
GetCurrentDirectory |
string GetCurrentDirectory(); |
Gets the current directory. |
GetDirectories |
string[] GetDirectories(stringPath); |
Gets an array of directories in the given directory. |
Move |
void Move(stringSourceDirName, stringDestDirName); |
Moves a directory and its contents to a new path. |