Home

The .NET Framework and its 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.

Practical LearningPractical Learning: Introducing Ancestor Classes

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
    
    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; }
        }
    }
    
    class Exercise
    {
        static int Main()
        {
    	Sport tennis = new Sport();
    
    	tennis.BallWeight      = 57.50; // grams
    	tennis.NumberOfPlayers = 1;     // Singles galme
    	tennis.CourtLength     = 23.70; // meters
    	tennis.CourtWidth      = 8.23;  // meters;
    
    	Console.WriteLine("\nGame 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;
        }
    }
  2. Save the file as exercise.cs in a new folder called Inherited created inside your CSharp Lessons folder
  3. Open the Command Prompt and switch to the folder that contains the current exercise
  4. Compile the program with csc exercise.cs
  5. Execute it by typing exercise
    Here is an example:
     
    C:\CSharp Lessons\Inherited>csc exercise.cs
    Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322
    Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
    
    C:\CSharp Lessons\Inherited>exercise
    
    Game Characteristics
    Ball Weight:           57.5 grams
    Players on each side:  1
    Court Dimensions(LxW): 23.7m X 8.23m
    
    C:\CSharp Lessons\Inherited>
  6. Return to Notepad
 

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 LearningPractical Learning: Implementing Equality

  1. To create your own implementation of the Equals() method, change the file as follows:
     
    using System;
    
    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 int GetHashCode()
        {
    	return base.GetHashCode();
        }
    
        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;
        }
    }
    
    class Exercise
    {
        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;
        }
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and test the application. This would produce:
     
    The Euro2002 and the tennis variables are not equal
    The Euro2002 and CAN2004 variables are equal
  4. Return to Notepad

Stringing a Class

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());
    }
}

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 LearningPractical Learning: Converting to String

  1. To implement and use a ToString() method, change the file as follows:
     
    using System;
    
    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 int GetHashCode()
        {
    	return base.GetHashCode();
        }
    
        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;
        }
    }
    
    class Exercise
    {
        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.Write("\nCup Game Characteristics");
             Console.WriteLine(CAN2004);
    
             Console.WriteLine();
    
    	Console.WriteLine("\nTennis Game Characteristics");
             Console.WriteLine(tennis);
    
             return 0;
        }
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and test 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
  4. Return to Notepad

Finalizing a Variable

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.

 

Built-In Assemblies and Classes

 

Introduction

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.

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 library 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
 

Custom Libraries

 

Introduction

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.

 

Creating a Library

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 LearningPractical Learning: Creating a Library

  1. Start a new file in Notepad and type the following in it:
     
    using System;
    
    namespace Arithmetic
    {
        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;
    	}
        }
    }
  2. Save the file in a new folder named Operations1
  3. Save the file itself as exo.cs
  4. Switch to the Command Prompt and change to the Operations1 folder
  5. To create the library, type csc /target:library /out:Arithmetic.dll exo.cs and press Enter
  6. Start another file in Notepad and type the following:
     
    using System;
    using Arithmetic;
    
    public class Exercise
    {
        static void Main()
        {
    	double Number1 = 244.58;
    	double Number2 = 5082.88;
    	double Result  = Operations.Addition(Number1, Number2);
    
    	Console.WriteLine("{0} + {1} = {2}\n", Number1, Number2, Result);
        }
    }
  7. Save the file in a new folder named Algebra1
  8. Save the file itself as Exercise.cs
  9. Switch to the Command Prompt and change to the Algebra1 folder
  10. To compile the program, type csc /reference:Arithmetic.dll Exercise.cs and press Enter
  11. To execute the application, type Exercise and press Enter
 
 

Previous Copyright © 2004-2006 FunctionX, Inc. Next