The Object class is a special type that is the base class for all other classes and types, including the value types. It defines a set of methods that are therefore inherited by every other type that is defined within the .NET framework class library.
What is the Object Class?
The Object class, held in the System namespace, is the base class for all classes and data types, including the value types. It is the class at the root of the .NET framework class library’s entire type hierarchy.
System.Object defines several public and protected methodsthat, due to inheritance, are automatically made available to all .NET classes, structures and types, including any classes or structures that you create yourself. If you create a class with no base class specified, it will implicitly derive functionality from Object.
Often developers overlookthe Object class. However, its importance is significant and the complexities if its members should be understood.
object = Object
The C# programming language declares a data type named “object”. This type is simply an alias for System.Object and so the two terms are interchangeable; they differ in capitalisation but not functionality.
The Object class defines seven base methods. Of these, five are public methods that are available to be called by external objects. The remaining two methods are protected. These are only accessible internally and to derived classes. Each of the methods is described in the following sections.
The Equals method is used to compare two objects to determine if they are equal. The comparison of the objects depends upon their types. For the value types, a bit-by-bit comparison of the two values is made. If they are a perfect match, the method returns true. If not, the method returns false.
When comparing reference types, the values of the two references are compared. Only when both references are pointing to the same object does the method return true. If the properties of two objects are a perfect match but the references are different, the method returns false.
The Equals method can be overridden in a subclass. This permits the behaviour to be changed so that it is more appropriate. For example, in the case of the string data type, Equals is overridden so that a comparison of two strings can be made as though they were value types. Even when the two strings contain different references, if the underlying characters match, the method returns true.
The Equals method is available in two forms. The instance version is shown in the above example. In this case, the method requires a single parameter containing the item to be compared to the invoking object. A static version of the method is also available. This requires two parameters, one for each of the items to be compared. The above example could therefore be rewritten as:
When overriding the behaviour of the Equals method, there are several rules that must be followed to ensure correct operation. These are:
- A call to x.Equals(x), where “x” is a variable of the class in question, must return true. The only exception to this rule is in the comparison of floating point data, where you may decide that a variable containing NaN (not a number) is not equivalent to itself. NB: Interestingly, the floating point types in the .NET framework return true when comparing NaN to NaN using the Equals method, but false when using the == operator. The == operator matches theIEC 60559:1989 specification whilst the Equals method does not.
- A call to x.Equals(y) must return the same result as a call to y.Equals(x).
- The expression “x.Equals(y) && y.Equals(z)” must only return true if x.Equals(z) returns true.
- If x and y are not modified, successive calls to x.Equals(y) must return consistent results.
- A call to x.Equals(null) must return false.
- If the == operator is overloaded, the Equals method must be overridden to provide matching functionality, except in the case of floating point value types.
- If Equals is overridden, the GetHashCode method must also be overridden for compatibility. Otherwise,Hashtables may function incorrectly.
- If a class implements the IComparable interface, the Equals method should be overridden.
- The Equals method must not throw exceptions.
The GetHashCode method provides an algorithm to generate a hash code for an object. Hash codes are used when creatinghash tables to permit objects to be found quickly in large sets of data. The GetHashCode method is used by the Hashtable collection class for this purpose.
The GetHashCode method returns an integer containing the hash code for an object. The value is not unique and should not be used as an identifier or for any purposes other than when using a hashing function. This is particularly relevant when using multiple versions of the .NET framework as the hashing algorithms for classes vary between versions, leading to different results for identical objects.
You can see examples of the return values by executing the following code. The results shown are generated using version 3.5 of the .NET framework and may differ from those you see.
The GetHashCode method can be overridden. When doing so, the following guidelines should be followed:
- If GetHashCode is overridden, the Equals method must also be overridden for compatibility. Otherwise, Hashtables may function incorrectly.
- The value returned from the hashing algorithm must be appropriate for value types. Two values that would be considered equal when using the Equals method must return the same hash code.
- The hash codes generated by the algorithm should be well distributed amongst the available range of integer return values. If the algorithm produces many duplicates or similar values, the performance of Hashtables will be impacted.
- The hashing algorithm should be as fast and efficient as possible to avoid performance issues with Hashtables.
- The GetHashCode method must not throw exceptions.
The GetType method simply returns the type of the object that invokes it. This is useful when using polymorphismtechniques as the type of the underlying object can be identified, even if held in a variable declared as another type. For example, if “Dog” is a subclass of “Animal” and a Dog object is being held in an Animal variable, the type returned will still be Dog. The method is also used for reflection.
The type is returned in a System.Type object. A detailed description of the System.Type class is beyond the scope of this article. For demonstration purposes we will simply output a string representation of the type to the console.
The ReferenceEquals method is a static member of the Object class. It is used with reference types to determine if two instances of a class contain the same reference. If the references are the same, the method returns true. If the references are different, the method returns false, even if the values of the two instances match. If the two items to be compared are both null, the resultant value is true. If they are two value types, the result is always false.
The method is called with two parameters, each holding one of the references to be compared.
The ToString method is probably the most well-known and used member of the Object class. This method returns a human-readable, string representation of the current object. The default behaviour is to return the fully qualified name of the object’s type. However, this can be overridden to provide a more useful value, as in the case of thenumeric types where the ToString method is overridden and overloaded to allow the creation of formatted numeric strings.
The base version of ToString provided by the Object class accepts no parameters.
The Finalize method is the first protected method of the Object class that we will consider. This method permits objects to clean up any resources and perform any other activities that are required before an object that is no longer required is reclaimed by the garbage collector. Finalizers in C# are declared as destructors.
The Finalize method cannot be overridden and may not be called during the normal execution of a program. The method is called automatically after an object is no longer accessible, due to all references to it being removed or going out of scope. However, there is no guarantee of the exact execution time of the Finalize method and certainly no assumption that it will run immediately should be made. It is also possible that the finalizer will not run at all if another Finalize method is blocked indefinitely or if the program terminates abnormally.
If two objects become inaccessible at the same time, there is no guarantee of the order in which their finalizers will be called. This is still the case when one of the objects refers to the other.
Classes must implement a destructor when they use unmanaged resources such as database connections or file handles. These resources cannot be reclaimed by the garbage collector and will otherwise not be correctly released. However, in these cases, the class should also implement the IDisposable interface.
The MemberwiseClone method is used to create a shallow copy of an object. A shallow copy of an object contains the same values and references as the original. For value type members, this is a bitwise copy of the member data. For reference type members the reference only is copied, meaning that the copy and the original are references to the same object. The method is called with no parameters and returns the cloned object as a System.Object that may be cast to the correct type as required.