Object Class in C#
- Every
class
in C#inherits
the property of theObject
class implicitly that is., theObject
class is thesuperclass
or super most class of each and every class.
using System;
class Base:Object {
public static void Main()
{
//using this class we can access all the properties of Base class and Object class.
}
}
Note: Even if we didn't inherit the
Object
classexplicitly
then also thecompiler
willimplicitly
inherit theObject
class to all the class.
- If some class is inheriting properties of other class then that class will not implicitly inherit the Object class because C# doesn't support the multiple inheritances.
using System;
class Super {
//This class will inherit the Object class implicitly.
}
class Base:Super, Object {
public static void Main()
{
//This class inherited the Superclass and we can't inherit implicitly or explicitly the Object class.
}
}
- We have some useful methods in the
Object
class which we can use in our program.
Methods of Object
class :
Equals(Object)
: Determines whether the specified object is equal to the current object.
Equals(Object, Object)
: Determines whether the specified object instances are considered equal.
Finalize()
: Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
GetHashCode()
: Serves as the default hash function.
GetType()
: Gets the Type of the current instance.
MemberwiseClone()
: Creates a shallow copy of the current Object.
ReferenceEquals(Object, Object)
: Determines whether the specified Object instances are the same instance.
ToString()
: Returns a string that represents the current object.
Overriding methods of Object class :
The
Object
class has multiple methods but we can onlyoverride
three methods from theObject
class.GetHashCode()
,Equals(Object)
, andToString()
only these methods of theObject
class can beoverridden
by the programmer.