In C#, an object may be referenced by any type in its inheritance hierarchy or by any of the interfaces it implements.
// Crow inherits from Bird, which inherits from Animal, and it implements IFly:class Bird : Animal{ }class Crow : Bird, IFly{ }// All of these references are valid:Crow crow = new Crow();Bird b = crow;Animal a = crow;IFly f = crow;
In C#, the functionality available to an object reference is determined by the reference’s type, not the object’s type.
Cat c = new Cat();Animal a = c;c.Meow(); // OK, 'Meow()' is defined for the type 'Cat'a.Meow();// Error! 'Meow()' is not defined for the type 'Animal'
In C#, the base class of all types is the Object
class. Every class implicitly inherits this class.
When you create a class with no inheritance, C# implicitly makes it inherit from Object
.
// When you write this code:class Dog {}// C# assumes you mean:class Dog : Object {}// Even if your class explicitly inherits from a class that is NOT Object, then some class in its class hierachy will inherit from Object. In the below example, Dog inherits from Pet, which inherits from Animal, which inherits from Object:class Dog : Pet {}class Pet : Animal {}class Animal {}// Since every class inherits from Object, any instance of a class can be referred to as an Object.Dog puppy = new Dog();Object o = puppy;
In C#, the Object
class includes definitions for these methods: ToString()
, Equals(Object)
, and GetType()
.
Object obj = new Object();Console.WriteLine(obj.ToString());// The example displays the following output:// System.Objectpublic static void Main(){MyBaseClass myBase = new MyBaseClass();MyDerivedClass myDerived = new MyDerivedClass();object o = myDerived;MyBaseClass b = myDerived;Console.WriteLine("mybase: Type is {0}", myBase.GetType());Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());}// The example displays the following output:// mybase: Type is MyBaseClass// myDerived: Type is MyDerivedClass// object o = myDerived: Type is MyDerivedClass// MyBaseClass b = myDerived: Type is MyDerivedClass
When a non-string object is printed to the console with Console.WriteLine()
, its ToString()
method is called.
Random r = new Random();// These two lines are equivalent:Console.WriteLine(r);Console.WriteLine(r.ToString());