Built-In Classes |
|
The Object Class |
Introduction |
C# was clearly created to improve on C++ and possibly offer a new alternative. To achieve this goal, Microsoft created a huge library to accompany the language. The .NET Framework is a huge library made of various classes and constants you can directly use in your C# application without necessarily explicitly loading an external library. To start, this main library of C# provides a class called Object. As you may have realized by now, every variable or function in C# (as in Java) must belong to a class, unlike C/C++ where you can have global variables or functions. Therefore, you always have to create at least one class for your application. As such, when you create a class, it automatically inherits its primary characteristics from the parent of all classes: Object. |
When you declare and initialize two variables, one of the operations you may want to subsequently perform is to compare their value. To support this operation, the Object class provides its children with a method called Equals. The Equals() method comes in two versions. The first has the following syntax: public virtual bool Equals(object obj); This version allows you to call the Equals() method on a declared variable and pass the other variable as argument. Here is an example: using System; class BookCollection { static void Main() { // First book int NumberOfPages1 = 422; // Second book int NumberOfPages2 = 858; // Third book int NumberOfPages3 = 422; if( NumberOfPages1.Equals(NumberOfPages2) == true ) Console.WriteLine("The first and the second books have the same number of pages"); else Console.WriteLine("The first and the second books have different number of pages"); if( NumberOfPages1.Equals(NumberOfPages3) == true ) Console.WriteLine("The first and the third books have the same number of pages"); else Console.WriteLine("The first and the third books have different number of pages"); } } This would produce: The first and the second books have different number of pages The first and the third books have the same number of pages The first version of the Object.Equals method is declared as virtual, which means you can override it if you create your own class. The second version of the Object.Equals() method is: public static bool Equals(object obj2, object obj2); As a static method, to use it, you can pass the variables of the two classes whose values you want to compare. In both cases, if the values of the variables are similar, the Equals() method returns true. If they are different, the method returns false. If you are using the Equals() method to compare the variables of two primitive types, the comparison should be straight forward. If you want to use this methods on variables declared from your own class, you should provide your own implementation of this method.
In previous lessons, we learned that, to convert the value of a variable declared from a primitive type to a string, you could call the ToString() function. Here is an example: using System; class BookCollection { static int Main() { int NumberOfPages = 422; Console.WriteLine("Number of Pages: {0}", NumberOfPages.ToString()); return 0; } } In many programming languages such as C++, programmers usually have to overload an (extractor) operator to display the value(s) of class' variable to the screen. The Object class provides an alternative to this somewhat complicated solution, through the ToString() method. It syntax is: public virtual string ToString(); Although the Object class provides this method as non abstract, its implemented version is more useful if you use a primitive type such as int, double and their variances or a string variable. The best way to rely on it consists of overriding it in your own class if you desired to use its role.
When we study inheritance, we will learn that all data types used in a C# program are "based on" an object called object. As introduced earlier, you can use this data type to declare a variable that would hold any type of value. Because this is some type of a "universal" data type, it can also be initialized with any value. Here are examples: using System; class Exercise { static void Main() { object Number = 244; object Thing = "Professor Kabba"; Console.WriteLine(Number); Console.WriteLine(Thing); } } This would produce: 244 Professor Kabba As you can see, when an object variable is initialized, the compiler finds out the type of value that was assigned to it. This is referred to as boxing. This mechanism is transparently done in C# (and in Visual Basic but not in Visual C++ 2003 (it is possible that something will be done in the next version, or not)). If you declare a variable using a primitive data type (int, float, double, etc), at one time, you may be interested in converting the value of that variable into an object. Here is an example: using System; class Exercise { static int Main() { int Number = 244; object Thing = Number; Console.WriteLine(Number); Console.WriteLine(Thing); return 0; } } This would produce: 244 244 This operation is referred to as unboxing. As you can see, this operation is performed transparently (Visual C++ 2003 doesn't do it transparently). Boxing and unboxing make C# a very flexible and wonderful language (if you misuse it, of course it can be dangerous).
While a constructor, created for each class, is used to instantiate a class. The Object class provides the Finalize() method as a type of destructor.
The System namespace provides one of the largest definition of classes of the .NET Framework, but it doesn't contain everything. For example, when you start writing graphical user interface (GUI) applications, you will have to use other namespaces. The namespaces are contained in libraries called assemblies. The actual classes used in various applications are created and defined in these libraries. Before using a class, you must know the name of the assembly in which it is defined. You must also know the name of its namespace. These three pieces of information, the name of the class, the namespace in which it is defined, and the name of the assembly in which the namespace is contained, are very important. Because there are so many classes, namespaces, and libraries, the MSDN documentation is your best reference. We can only mention a few, especially those that are relevant for the subjects we are reviewing.
Imagine you have a series of numbers, such these: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, and 20. Imagine you want to select one of these numbers, any of them. A number is referred to as random if it has been selected from a pool without a specific pattern to follow. For example, if you decide to select the value 17 from this list, if there was an exact reason that number was selected, then it is not considered random. In reality, it is difficult for a number to qualify as random. For this reason, most random numbers are referred to as pseudo-random.
To support the ability to create or choose a random number, the .NET Framework provides the Random class. To start, you can declare a variable of this class, using one of its two constructors. Here is an example that uses the default constructor: using System; class Program { static int Main() { Random rndNumber = new Random(); return 0; } } After creating the variable, you can start getting numbers from it. To do this, you call the Next() method, which is overloaded in three versions. One of the versions of this method takes no argument and its syntax is: public virtual int Next(); This method generates a randomly selected integer between 0 and the MinValue value of the int data type. Here is an example: using System; class Program { static int Main() { Random rndNumbers = new Random(); int rndNumber = rndNumbers.Next(); Console.WriteLine("Number: {0}", rndNumber); return 0; } } Here is an example of running the program: Number: 1369872590 Press any key to continue . . . In the same way, you can call this version of the Next() method repeatedly to get random. Here is an example: using System; class Program { static int Main() { Random rndNumbers = new Random(); int rndNumber = 0; for (int nbr = 1; nbr < 9; nbr++) { rndNumber = rndNumbers.Next(); Console.WriteLine("Number: {0}", rndNumber); } return 0; } } Here is an example of running the program: Number: 1924504148 Number: 1257846191 Number: 424740120 Number: 1009211682 Number: 544356245 Number: 708951978 Number: 759684741 Number: 1325535324 Press any key to continue . . .
Consider the following program: using System; class Program { static int Main() { Random rndNumbers = new Random(); int rndNumber = rndNumbers.Next(); Console.WriteLine("Number: {0}", rndNumber); return 0; } } Here is an example of running the program: Number: 573991745 Press any key to continue . . . Here is another example of running the same program: Number: 334223329 Press any key to continue . . . Notice that the numbers generated are different. When creating a program that repeatedly gets a series of random numbers, you may (or may not) want the Random class to generate the same number over and over again. A seed is a constant value that controls whether a random generation would produce the same result every time it occurs. For example, using a seed, you can impose it upon the Random class to generate the same number every time the Next() method is called. To support the ability to use a seed, the Random class is equipped with a second constructor whose syntax is: public Random(int Seed); Based on this, to specify a seed, when declaring a Random variable, pass a constant integer to the constructor. Here is an example: using System; class Program { static int Main() { Random rndNumbers = new Random(20); int rndNumber = rndNumbers.Next(); Console.WriteLine("Number: {0}", rndNumber); return 0; } } Here is one example of running the program: Number: 375271809 Press any key to continue . . . Here is another example of running the same program: Number: 375271809 Press any key to continue . . . Notice that the numbers are the same. Consider this program also: using System; class Program { static int Main() { Random rndNumbers = new Random(20); int rndNumber = 0; for (int nbr = 1; nbr < 5; nbr++) { rndNumber = rndNumbers.Next(); Console.WriteLine("Number: {0}", rndNumber); } return 0; } } Here is one example of running the program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press any key to continue . . . Here is another example of running the same program: Number: 375271809 Number: 1472524622 Number: 1605850688 Number: 1776011503 Press any key to continue . . . Notice that the sequences are the same. In both cases, this indicates that, if you specify a seed, the Random class would generate the same number or the same sequence of numbers.
So far, we have been using with any number that would fit an integer. In some assignments, you may want to restrict the range of numbers that can be extracted. Fortunately, the Random class allows this. Using the Random class, you can generate random positive numbers up to a maximum of your choice. To support this, the Random class is equipped with another version of the Next() method whose syntax is: public virtual int Next(int maxValue); The argument to pass to the method determines the highest integer that can be generated by the Next() method. The method returns an integer. Here is an example that generates radom numbers from 0 to 20: using System; class Program { static int Main() { Random rndNumbers = new Random(); int rndNumber = 0; for (int nbr = 1; nbr < 9; nbr++) { rndNumber = rndNumbers.Next(20); Console.WriteLine("Number: {0}", rndNumber); } return 0; } } Here is an example of running the program: Number: 1 Number: 7 Number: 1 Number: 16 Number: 14 Number: 19 Number: 3 Number: 1 Press any key to continue . . . The above version of the Next() method generates numbers starting at 0. If you want, you can specify the minimum and the maximum range of numbers that the Next() method must work with. To support this, the Random class is equipped with one more version of this method and that takes two arguments. Its syntax is: public virtual int Next(int minValue, int maxValue); The first argument specifies the lowest value that can come from the range. The second argument holds the highest value that the Next() method can generate. Therefore, the method would operate between both values. Here is an example that generates random numbers from 6 to 18: using System; class Program { static int Main() { Random rndNumbers = new Random(); int rndNumber = 0; for (int nbr = 1; nbr < 9; nbr++) { rndNumber = rndNumbers.Next(6, 18); Console.WriteLine("Number: {0}", rndNumber); } return 0; } } Here is an example of running the program: Number: 17 Number: 9 Number: 8 Number: 15 Number: 10 Number: 9 Number: 13 Number: 11 Press any key to continue . . . Notice that the numbers are between 6 and 18.
One of the strengths of Visual Basic, from its beginning, was its huge library of functions. Unfortunately, even when Visual Basic was part of the Visual Studio 6.0 environment, its functions belonged only to it and to its child languages such as VBA and VBScript. When Visual Studio .NET was created, the developers of Visual Basic added all of its valuable functions and in fact made them available to the other languages that use the .NET Framework. This means that those wonderful functions are available to use in your C# programs. The functions of Microsoft Visual Basic still belong to it and they can be called transparently in a Visual Basic application. If you want to use them in a non-Visual Basic application, you must remember to reference its library. Most (if not all) of the functions of Visual Basic are created in the Microsoft.VisualBasic.dll assembly but they might be in different namespaces. Based on this, you can include any Visual Basic function in your program. Here is an example:
When compiling the program, you must reference the Microsoft.VisualBasic.dll library. Here is an example: csc /reference:Microsoft.VisualBasic.dll Exercise.cs
If the .NET Framework doesn't have a class you are looking for, you can create one and be able to use it over and over again in different programs. You can even create a commercial class and be able to distribute or sell it. To make this possible, you can "package" one or more classes in a library. A library is a program that contains classes and/or other resources that other programs can use. Such a program is created with the same approach as the programs we have done so far. Because a library is not an executable, it doesn't need the Main() function. A library usually has the extension .dll.
A library can be made of a single file or as many files as necessary. A file that is part of a library can contain one or more classes. Each class should implement a behavior that can eventually be useful and accessible to other classes. The classes in a library are created exactly like those we have used so far. Everything depends on how you compile it. To create a library, start by typing its code in a text file. Once the library is ready, to compile it, at the Command Prompt, you would type: csc /target:library NameOfFile.cs and press Enter. After doing this, a library with the name of the file and the extension .dll would be created. If you want a custom name, use the following syntax: csc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.cs
|
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operations1 { public class Operations { public static double Addition(double x, double y) { return x + y; } public static double Subtraction(double x, double y) { return x - y; } public static double Multiplication(double x, double y) { return x * y; } public static double Division(double x, double y) { if (y == 0) return 0; return x / y; } } } |
using System; namespace Algebra1 { class Program { static int Main() { double Number1 = 244.58; double Number2 = 5082.88; double Result = Operations1.Operations.Addition(Number1, Number2); Console.WriteLine("{0} + {1} = {2}\n", Number1, Number2, Result); return 0; } } } |
244.58 + 5082.88 = 5327.46 Press any key to continue . . . |
One of the most important sought goals in .NET is to allow different languages to collaborate, such as sharing code. One way this can happen is to be able to use the functionality of one language into another. As an illustration, we saw earlier that you could use the rich library of Visual Basic functions in a C# application. As no library is ever complete, you may still need functionality that is not easily found. Furthermore, you may be working with a team of C++ programmers who have already created a set of functions or complex operations. You should be able to use that existing code.
In previous years, it used to be a challenge to create a library, especially in C++. Fortunately, Microsoft Visual C++ now makes it particularly easy to create one, because a wizard highly assists you. To create a library, first display the New Project dialog box. After specifying Visual C++, in the Templates list, click Class Library and give it a name. In the body of the file, you can create the classes and/or functions as you see fit. Here is an example: // Business.h #pragma once using namespace System; namespace Business { public ref class Finance { public: double CalculateDiscount(double MarkedPrice, double DiscountRate) { return MarkedPrice * DiscountRate / 100; } }; } Once the project is ready, you must build it (on the main menu, Build -> Build Business). As a result, the compiler would create a file with the .dll extension: Normally, as far as creating a library, that's it.
Creating a library in C++ is easy. To use it, there are a few rules you must follow. To start, you must make sure that your project can "physically" find the library. Probably the easiest way to take care of this is to copy the dll file and paste it in the folder that contains your project's executable. You can also do this directly in Visual Studio by importing the library file as we saw earlier. In your project, you should include the System.Runtime.InteropServices namespace. Before the section where the library will be accessed, enter the DllImport attribute that takes as argument the name of the library passed as a string. Here is an example: using System; using System.Runtime.InteropServices; using Business; namespace DepartmentStore { class Exercise { [DllImport("Business.dll")] public static extern double CalculateDiscount(double price, double discount) static int Main() { Finance fin = new Finance(); double markedPrice = 275.50; double discountRate = 25.00; // % double discountAmount = fin.CalculateDiscount(markedPrice, discountDate); double netPrice = markedPrice - discountAmount); Console.WriteLine("Marked Price: {0:C}", markedPrice); Console.WriteLine("Discount Rate: {0:P}", discountRate / 100); Console.WriteLine("Discount Amount: {0:C}", discountAmount); Console.WriteLine("Net Price: {0:C}\n", netPrice); return 0; } } } This makes your library code ready to be used, which you can do as you would any other code. This means that you can compile your program the way we did in the previous section.
The Microsoft Windows operating system was originally written in C, the parent language of C++ and C# (also of Java and JavaScript). To allow programmers to create applications, Microsoft released a library called Win32. This is a series of functions and classes, etc, that you previously had to use. As time has changed, you don't need to exclusively use Win32 anymore to create a Windows application. Nonetheless, Win32 is still everywhere and it is not completely avoidable because many or some of the actions you would want to perform in a Windows application are still available only in Win32. Fortunately, in most cases, it is not always difficult to use some of these functions in a C# applications, as long as you observe some rules. Here is an example: using System; using System.Runtime.InteropServices; namespace Win32Applied { class Program { [DllImport("Kernel32.dll")] public static extern bool SetConsoleTitle(string strMessage); static int Main() { SetConsoleTitle("C# Programming"); return 0; } } }
|
|
||
Previous | Copyright © 2008-2016, FunctionX, Inc. | Next |
|