|
Practical
Learning: Introducing Ancestor Classes
|
|
- Start Microsoft Visual C# and create a Console
Application named Sport1
- To create a new class, in the Solution Explorer, right-click Sport1
-> Add -> Class...
- Set the Name to Sport and click Add
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Sport
{
private double _ballWeight;
private int _players;
private double _courtLength;
private double _courtWidth;
public double BallWeight
{
get { return _ballWeight; }
set { _ballWeight = value; }
}
public int NumberOfPlayers
{
get { return _players; }
set { _players = value; }
}
public double CourtLength
{
get { return _courtLength; }
set { _courtLength = value; }
}
public double CourtWidth
{
get { return _courtWidth; }
set { _courtWidth = value; }
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Program
{
static int Main()
{
Sport tennis = new Sport();
tennis.BallWeight = 57.50; // grams
tennis.NumberOfPlayers = 1; // Singles game
tennis.CourtLength = 23.70; // meters
tennis.CourtWidth = 8.23; // meters;
Console.WriteLine("Sport Characteristics");
Console.WriteLine("Ball Weight: {0} grams",
tennis.BallWeight);
Console.WriteLine("Players on each side: {0}",
tennis.NumberOfPlayers);
Console.WriteLine("Court Dimensions(LxW): {0}m X {1}m\n",
tennis.CourtLength, tennis.CourtWidth);
return 0;
}
}
}
|
- Execute the application:
Sport Characteristics
Ball Weight: 57.5 grams
Players on each side: 1
Court Dimensions(LxW): 23.7m X 8.23m
Press any key to continue . . .
|
- Close the DOS window
|
Equality of Two Class Variables
|
|
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.
|
Practical
Learning: Implementing Equality
|
|
- Access the Sport.cs file
- To create your own implementation of the Equals() method,
change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Sport
{
. . .
public double CourtWidth
{
get { return _courtWidth; }
set { _courtWidth = value; }
}
public override bool Equals(Object obj)
{
Sport sp = (Sport)obj;
if ((_ballWeight == sp._ballWeight) &&
(_players == sp._players) &&
(_courtLength == sp._courtLength) &&
(_courtWidth == sp._courtWidth))
return true;
return false;
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Program
{
static int Main()
{
Sport Euro2002 = new Sport();
Sport CAN2004 = new Sport();
Sport tennis = new Sport();
Euro2002.BallWeight = 435; // grams
Euro2002.NumberOfPlayers = 11; // persons for each team
Euro2002.CourtLength = 100; // meters
Euro2002.CourtWidth = 60; // meters
tennis.BallWeight = 57.50; // grams
tennis.NumberOfPlayers = 1; // Singles game
tennis.CourtLength = 23.70; // meters
tennis.CourtWidth = 8.23; // meters;
CAN2004.BallWeight = 435; // grams
CAN2004.NumberOfPlayers = 11; // persons for each team
CAN2004.CourtLength = 100; // meters
CAN2004.CourtWidth = 60; // meters
if (CAN2004.Equals(tennis) == true)
Console.WriteLine("The CAN2004 and the tennis variables are equal");
else
Console.WriteLine("The Euro2002 and the tennis variables are not equal");
if (Euro2002.Equals(CAN2004) == true)
Console.WriteLine("The Euro2002 and CAN2004 variables are equal");
else
Console.WriteLine("The Euro2002 and CAN2004 variables are not equal");
return 0;
}
}
}
|
- Execute the application. This would produce:
The Euro2002 and the tennis variables are not equal
The Euro2002 and CAN2004 variables are equal
Press any key to continue . . .
|
- Close the DOS window
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.
|
Practical
Learning: Converting to String
|
|
- Access the Sport.cs file
- To implement and use a ToString() method, change the file as
follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Sport
{
private double _ballWeight;
private int _players;
private double _courtLength;
private double _courtWidth;
public double BallWeight
{
get { return _ballWeight; }
set { _ballWeight = value; }
}
public int NumberOfPlayers
{
get { return _players; }
set { _players = value; }
}
public double CourtLength
{
get { return _courtLength; }
set { _courtLength = value; }
}
public double CourtWidth
{
get { return _courtWidth; }
set { _courtWidth = value; }
}
public override bool Equals(Object obj)
{
Sport sp = (Sport)obj;
if ((_ballWeight == sp._ballWeight) &&
(_players == sp._players) &&
(_courtLength == sp._courtLength) &&
(_courtWidth == sp._courtWidth))
return true;
return false;
}
public override string ToString()
{
string person = null;
if (NumberOfPlayers.Equals(1))
person = " person";
else
person = " persons";
string result =
"\nBall Weight: " + BallWeight + " grams" +
"\nPlayers on each side: " + NumberOfPlayers + person +
"\nCourt Dimensions(LxW): " +
CourtLength + "m X " + CourtWidth + "m";
return result;
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sport1
{
class Program
{
static int Main()
{
Sport CAN2004 = new Sport();
Sport tennis = new Sport();
tennis.BallWeight = 57.50; // grams
tennis.NumberOfPlayers = 1; // Singles game
tennis.CourtLength = 23.70; // meters
tennis.CourtWidth = 8.23; // meters;
CAN2004.BallWeight = 435; // grams
CAN2004.NumberOfPlayers = 11; // persons for each team
CAN2004.CourtLength = 100; // meters
CAN2004.CourtWidth = 60; // meters
Console.WriteLine("====================================");
Console.WriteLine("Cup Game Characteristics");
Console.Write("------------------------------------");
Console.WriteLine(CAN2004);
Console.WriteLine("\n====================================");
Console.WriteLine("Tennis Game Characteristics");
Console.Write("------------------------------------");
Console.WriteLine(tennis);
Console.WriteLine("\n====================================");
return 0;
}
}
}
|
- Execute the application. This would produce:
====================================
Cup Game Characteristics
------------------------------------
Ball Weight: 435 grams
Players on each side: 11 persons
Court Dimensions(LxW): 100m X 60m
====================================
Tennis Game Characteristics
------------------------------------
Ball Weight: 57.5 grams
Players on each side: 1 person
Court Dimensions(LxW): 23.7m X 8.23m
====================================
Press any key to continue . . .
|
- Close the DOS window
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 . . .
|
The Seed of a Random Number
|
|
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.
|
Generating Random Numbers in a Range 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.
|
Built-In Assemblies and Libraries
|
|
|
Microsoft Visual Basic Functions
|
|
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:
| Source File: Exercise.cs |
using System;
class Exercise
{
static void Main()
{
double Number;
double Result;
Console.Write("Enter a number: ");
string strNbr = Console.ReadLine();
if( !Microsoft.VisualBasic.Information.IsNumeric(strNbr) )
Number = 0.00;
else
Number = Microsoft.VisualBasic.Conversion.Val(strNbr);
Result = Number * 2;
Console.WriteLine("{0} * 2 = {1}", Number, Result);
}
}
|
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
|
Practical
Learning: Creating a Library
|
|
- To start a new project, on the main menu, click File -> New Project...
- In the New Project dialog box, click Class Library
- Set the Name to Operations1 and click OK
- Change the file as follows:
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;
}
}
}
|
- In the Solution Explorer, right-click Class1.cs and click Rename
- Change the name to Operations.cs and press Enter
- To save the project, on the Standard toolbar, click the Save All button

- Click Save to save everything
- On the main menu, click Project -> Operations1 Properties
- In the Output Type combo box, make sure Class Library is selected:

- Click the X button to close the Properties window
- To create the library, on the main menu, click Build -> Build Solution
- To start another project, on the main menu, click File -> New
Project...
- In the New Project dialog box, select Console Application
- Set the Name to Algebra1 and press Enter
- In the Solution Explorer, right-click References and click Add
Reference...
- Click the Browse tab
- In the list of folders, double-click Operations1 and locate the
Operations1.dll file (it should be in the Release (or the Debug) sub-folder
of the bin folder)
- Click Operations1.dll

- Click OK.
In the Solution Explorer, expand the References node if necessary and make
sure that there is a new node labeled Operations1
- Access the Program.cs file and change it as follows:
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;
}
}
}
|
- Execute the application to test it. This would produce:
244.58 + 5082.88 = 5327.46
Press any key to continue . . .
|
- Close the DOS window
|
A Library Created in Another Language
|
|
|
Using a Visual C++/CLI Library
|
|
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;
}
}
}
|