Home

Built-In Classes: Object

 

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 Microsoft Visual C# and create a Console Application named Sport1
  2. To create a new class, in the Solution Explorer, right-click Sport1 -> Add -> Class...
  3. Set the Name to Sport and click Add
  4. Change the file as follows:
     
    using System;
    
    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; }
            }
        }
    }
  5. Access the Program.cs file and change it as follows:
     
    using System;
    
    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;
            }
        }
    }
  6. 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 . . .
  7. 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 LearningPractical Learning: Implementing Equality

  1. Access the Sport.cs file
  2. To create your own implementation of the Equals() method, change the file as follows:
     
    using System;
    
    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;
            }
        }
    }
  3. Access the Program.cs file and change it as follows:
     
    using System;
    
    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;
            }
        }
    }
  4. 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 . . .
  5. Close the DOS window

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. Access the Sport.cs file
  2. To implement and use a ToString() method, change the file as follows:
     
    using System;
    
    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;
            }
        }
    }
  3. Access the Program.cs file and change it as follows:
     
    using System;
    
    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;
            }
        }
    }
  4. 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 . . .
  5. Close the DOS window

Boxing and Un-Boxing

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 void Main()
	{
		int Number = 244;
		object Thing  = Number;

		Console.WriteLine(Number);
		Console.WriteLine(Thing);
	}
}

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).

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.

Other Built-In Classes

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.

 

Home Copyright © 2006 FunctionX, Inc.