Thanks Bruce. This is a timely topic for me.
The SayHello method signature includes a person parameter of type IGreeting.
If the person parameter is an object of type IGreeting where does the person
object get its string data that is then passed through as a value to the
person.Hello parameter of the WriteLine method?
<%= Clinton Gallagher
Bruce Wood said:
My question is, if you must declare each method (as opposed to simply
'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What
advantage does using an interface have if you must manually declare
all the methods anyway?
The answer is something called "polymorphism": if you declare a bunch
of classes as implementing the same interface, then you can write code
that can operate on any of those classes, because the code knows that
they all implement the same interface methods with the same calling
sequences (signatures). As a (stupid) example, if I were to have an
interface:
public interface IGreeting
{
public string Hello { get; }
public void ShakeHands();
}
and I write a couple of classes:
public class English : IGreeting
{
public string Hello { get { return "Hello"; } }
public void ShakeHands() { // Do some stuff here }
}
public class Spanish : IGreeting
{
public string Hello { get { return "Buenos días"; } }
public void ShakeHands() { // Do some stuff here }
}
then I could write a method in some other class:
public void SayHello(IGreeting person)
{
Console.WriteLine(person.Hello);
person.ShakeHands();
}
"SayHello" can say hello and shake hands without knowing what kind of
person it is, because it knows that all objects passed to it must
implement the IGreeting interface, and so must have a "Hello" string
property and a "ShakeHands" method that takes no arguments.
Without the interface, there would be no way to express, "An object
that has a Hello string property and a ShakeHands void method that
takes no arguments."
(By the way, a picky detail about terminology: the interface _declares_
the properties, methods, and events. The class either _implements_ them
or _defines_ them (they both mean the same thing, really). Yes, the
class also declares them again, but that's not so important as the idea
that it implements them.)