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.

 

ApplicationApplication: Introducing Ancestor Classes

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to UtilityCompany1 and press Enter
  5. To create a new class, in the Class View, right-click UtilityCompany1 -> Add -> Class...
  6. Set the Name to Customer and click Add
  7. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private long acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
        }
    }
  8. In the document, right-click acnt, position the mouse on Refactor, and click Encapsulate Field...
  9. In the Encapsulate Field dialog box, change the name to AccountNumber
     
    Encapsulate Field
  10. Click OK
  11. In the Preview Reference Changes dialog box, check the code and click Apply
  12. In the document, right-click fn -> Refactor -> Encapsulate Field...
  13. In the Encapsulate Field dialog box, change the name to FullName
  14. Click OK
  15. In the Preview Reference Changes dialog box, check the code and click Apply
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
        }
    }
  16. To create a new file, in the Solution Explorer, right-click UtilityCompany1 -> Add -> New Item...
  17. In the middle list, click Code File...
  18. Change the Name to AccountProcessing and click Add
  19. In the empty document, type the following:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        public Customer Register()
        {
            string accountNumber;
            string custName;
    
            Console.WriteLine("============================");
            Console.WriteLine("Utility Bill");
            Console.WriteLine("----------------------------");
            Console.WriteLine("Enter Customer Information");
            Console.Write("Account Number: ");
            accountNumber = Console.ReadLine();
            Console.Write("Customer Name:  ");
            custName = Console.ReadLine();
    
            Customer cust = new Customer(accountNumber, custName);
            return cust;
        }
    
        public void CreateUtilityBill(Customer custInfo)
        {
            Console.WriteLine("============================");
            Console.WriteLine("Utility Bill");
            Console.WriteLine("----------------------------");
            Console.WriteLine("Customer Name:  {0}", custInfo.AccountNumber);
            Console.WriteLine("Account Number: {0}", custInfo.FullName);
            Console.WriteLine("============================");
        }
    
        public static int Main()
        {
            Customer cust = null; // new Customer();
            ProcessingAccount pa = new ProcessingAccount();
    
            Console.WriteLine("Utility Company");
            cust = pa.Register();
    
            Console.Clear();
    
            pa.CreateUtilityBill(cust);
            System.Console.ReadKey();
    
            return 0;
        }
    }
  20. To execute the application, on the main menu, click Debug -> Start Debugging
  21. When requested, enter the account number as 28-614007-59 and press Enter
  22. Enter the name as George Sandt and press Enter

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.

ApplicationApplication: Implementing Equality

  1. Access the Customer.cs file
  2. 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 UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
    
            public override bool Equals(object obj)
            {
                Customer cust = (Customer)obj;
    
                if( (acnt == cust.acnt) &&
                    (fn == cust.fn) )
                    return true;
    
                return false;
            }
        }
    }
  3. Access the AccountProcessing.cs file and change it as follows:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        . . . No Change
    
        public static int Main()
        {
            var first = new Customer("72-975947-64", "James Barans");
            var second = new Customer("50-315759-95", "Paul Motto");
            var third = new Customer("72-975947-64", "James Barans");
    
            if (first.Equals(second))
            {
                Console.Write("The first and the second records ");
                Console.WriteLine("represent the same customer.");
            }
            else
                Console.WriteLine("The first and the second records are different.");
    
            if (first.Equals(third))
            {
                Console.Write("The first and the third records ");
                Console.WriteLine("represent the same customer");
            }
            else
                Console.WriteLine("The first and the third records are different.");
            
            System.Console.ReadKey();
            return 0;
        }
    }
  4. To execute the application, on the main menu, click Debug -> Start Debugging. This would produce:
    The first and the second records are different.
    The first and the third records represent the same customer
  5. Close the DOS window

Stringing an Object

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.

ApplicationApplication: Converting to String

  1. Access the Customer.cs file
  2. 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 UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
    
            public override bool Equals(object obj)
            {
                Customer cust = (Customer)obj;
    
                if( (acnt == cust.acnt) &&
                    (fn == cust.fn) )
                    return true;
    
                return false;
            }
    
            public override string ToString()
            {
                return "Customer Name:  " + acnt +
                       "\nAccount Number: " + fn;
            }
        }
    }
  3. Access the AccountProcessing.cs file and change it as follows:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        public Customer Register()
        {
            string accountNumber;
            string custName;
    
            Console.WriteLine("============================");
            Console.WriteLine("Utility Bill");
            Console.WriteLine("----------------------------");
            Console.WriteLine("Enter Customer Information");
            Console.Write("Account Number: ");
            accountNumber = Console.ReadLine();
            Console.Write("Customer Name:  ");
            custName = Console.ReadLine();
    
            Customer cust = new Customer(accountNumber, custName);
            return cust;
        }
    
        public void CreateUtilityBill(Customer custInfo)
        {
            Console.WriteLine("============================");
            Console.WriteLine("Utility Bill");
            Console.WriteLine("----------------------------");
            Console.WriteLine(custInfo);
            Console.WriteLine("============================");
        }
    
        public static int Main()
        {
            Customer cust = null; // new Customer();
            ProcessingAccount pa = new ProcessingAccount();
    
            Console.WriteLine("Utility Company");
            cust = pa.Register();
    
            Console.Clear();
    
            pa.CreateUtilityBill(cust);
            System.Console.ReadKey();
            
            return 0;
        }
    }
  4. To execute the application, on the main menu, click Debug -> Start Debugging
  5. When requested, enter the account number as 44-204814-18 and press Enter
  6. Enter the name as William Bohden and press Enter
  7. 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 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).

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 © 2009-2011 FunctionX