Consider the following code for a v1.0 release.
public interface ITalk
{
void Talk();
}
public class Loud : ITalk
{
public void Talk()
{
System.Console.WriteLine("!!!");
}
}
class program
{
public static void Main(System.String[] args)
{
ITalk t;
t = new Loud();
t.Talk();
}
}
The output of running hellow.exe is: !!!
Consider the following code for a v2.0 release. The changed assembly is only shipped and overwrites the v1.0 assembly.
public interface ITalk
{
void Talk();
void Whisper();
}
So the question becomes: what will happen when hellow.exe is run with the new assembly?
The output of running hellow.exe is: Unhandled Exception: System.TypeLoadException: Method 'Whisper' in type 'Loud' from assembly 'loud, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' doesnot have an implementation. at program.Main(String[] args)
This makes sense; the v1.0 concrete type does not implement all of v2.0 interface's members.
Why is this important? There are many scenarios when you see Microsoft use classes instead of interfaces and say why? This scenario is the reason. Interfaces in public APIs are considered closed for modification (immutable) (see the open-closed principle). The COM technology relied on this concept; this is why you would see COM interfaces for example IWebBrowser, IWebBrowser2, et. al. Binary compatibility must be maintained in shared components.
Using classes, you can extend a type for v2, while still allowing for binary compatibility. Consider the revised following code.
public abstract class Talk
{
public abstract void Talk();
}
public class Loud : Talk
{
public override void Talk()
{
System.Console.WriteLine("!!!");
}
}
class program
{
public static void Main(System.String[] args)
{
Talk t;
t = new Loud();
t.Talk();
}
}
The output of running hellow.exe is: !!!
Consider the following code for a revised v2.0 release. Again, the changed assembly is only shipped and overwrites the v1.0 assembly.
public abstract class Talk
{
public abstract void Talk();
public virtual void Whisper() { // default impl }
}
So the question becomes: what will happen when hellow.exe is run with the new assembly?
The output of running hellow.exe is: !!!
Since the revised v2 additional member has a default but virtual implementation, the type load succeeds and all is well. This ensures binary compatibility.