This is from a C# primer presentation for fellow consultants at the company I work for. I have been concentrating on the finer points of interfaces and how they work, what there purpose is and some example implementations.
When I had implemented interfaces before I always assumed that if you declared an interface like:
interface IFix { void Heal(); }
The following two implementations of void Heal() would meet the interface contract in the same way:
class Person : IFix
{
public void Heal()
{
Console.WriteLine("Person::Save");
}
}
equal to:
class Person: IFix
{
//explicit
void IFix.Heal()
{
Console.WriteLine("Patient::Save");
}
}
Well it's not a stylistic difference like I first thought. Take a look at these examples for yourself:
ISemantics.cs
using System;
namespace InterfaceSemantics
{
interface IFix { void Heal(); }
class Person : IFix
{
public void Heal()
{
Console.WriteLine("Person::Save");
}
}
class Doctor : Person
{
public new virtual void Heal()
{
Console.WriteLine("Doctor::Save");
}
}
class Surgeon : Person, IFix
{
//explicit
public new virtual void Heal()
{
Console.WriteLine("Surgeon::Save");
}
}
class Patient : IFix
{
//explicit
void IFix.Heal()
{
Console.WriteLine("Patient::Save");
}
}
}
form1.cs (partial - Form1_Load)
private void Form1_Load(object sender, System.EventArgs e)
{
Doctor doc = new Doctor();
doc.Heal();
Person basecls = (Person)doc;
basecls.Heal();
//This impl you can access the interface through the class.
Surgeon cutter = new Surgeon();
cutter.Heal();
//still works
IFix isurg = (IFix)cutter;
isurg.Heal();
//Using explicit declaration of the interface
Patient pat = new Patient();
IFix iface = (IFix)pat;
iface.Heal();
//This impl needs a request for the interface
//Here we get a compilation error:
// 'InterfaceSemantics.Patient' does not contain a definition for 'Heal'
//
//for code:
Patient pat = new Patient();
pat.Heal();
//because we used void IFix.Heal() as the prototype to fulfill the interface contract
}