Reputation: 760
Consider the following example.
public interface IAnimal
{
void MakeSound();
}
public class Dog: IAnimal
{
public void MakeSound() { Console.WriteLine("Bow-Bow-Bow"); }
public static void Main()
{
IAnimal a = new Dog();
Console.WriteLine(a.MakeSound());
Console.WriteLine(a.ToString());
}
}
How come the interface instance can access ToString method that was from System.Object? My understanding is, with interface, one can access only the methods the interface holds.
Upvotes: 2
Views: 236
Reputation: 42689
My understanding is, with interface, one can access only the methods the interface holds.
Actually, with an interface you can access the methods the interface holds and all members of System.Object
(as you have discovered). This doesn't mean that interfaces themselves derives from System.Object
, it just means that the compiler has a "special case" when checking for members on variables declared as interfaces.
The compiler can do this because interfaces are implemented by objects and all objects derive from System.Object
.
So when a
is declared as IAnimal
it really means that the variable a
contains an object which implement the interface IAnimal
. This object is guaranteed to support all members in IAnimal
and all members System.Object
.
Upvotes: 0
Reputation: 89325
Your class implicitly derived from System.Object
:
Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit. [MSDN]
UPDATE :
Just found this, possible duplicate? :
Do interfaces derive from System.Object? C# spec says yes, Eric says no, reality says no
Upvotes: 4
Reputation: 31
Because everything is an object. It's a cheeseball answer, but that's how .NET works. :)
Upvotes: 2