I think your example is very bad: because what you should do in your class is
override the
ToString
method it inherited from
System.Object
, not
replace it (what you did, and you did it wrong - look at the compiler warning (you should use the
new
keyword on the method declaration)).
So implicit your ClassA is defined like this
class ClassA : System.Object, IMyInterface
.
There for it has a ToString method you can call (btw. it won't call yours!!!!)
Try for yourself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CallInterface
{
interface IMyInterface
{
void ShowMe();
}
class ClassA : IMyInterface
{
public void ShowMe()
{
Console.WriteLine("ClassA");
}
public void Display()
{
Console.WriteLine("Display");
}
public string ToString()
{
Console.WriteLine("ToString Class");
return "";
}
}
class Program
{
static void Main(string[] args)
{
IMyInterface objClass = new ClassA();
objClass.ShowMe();
objClass.ToString();
Console.ReadKey();
}
}
}
Conclusion: Your question is "bad" because your understanding of what an interface is and how inheritance works is wrong.
* you don't override interface methods - you implement them
* if you know the type of an object (or can test for a concrete type like ClassA)
you can recast your interface typed object to the concrete type and call your method:
ClassA classA = objClass as ClassA;
if(classA != null)
classA.Display();
* your example code won't compile (a lot of errors) - so maybe implement a real example (like I did above) play with it, will give you a better understanding.
* What SA told you is why a ToString method is found on any Interface type, but I don't think you even thought about that.
So:
* play with an example
* read (again) about inheritance, interfaces, and
override
vs.
new
in C#
* Try to understand when to use each of these patterns
* Use interfaces the right way and you won't ask questions like this (because if you wonder "why can't I call this method" most likely your architecture is wrong.