A while ago I had a small problem with interface ambiguity. The subject can be quite tricky to understand, so I decided to write a small blog post about the problem. This problem occurs when to interfaces implement the same property and a third interface tries to implement that property. Any references to that property through the third interface will result in a wonderful Ambiguity between 'xxx.yyy' and 'zzz.yyy'.
So let's jump in and consider the following interfaces:
public interface IShippable
{
string Size { get; set; }
string LabelText { get; set; }
}
public interface IAnimal
{
string Size { get; set; }
string Name { get; set; }
}
public interface IZooAnimal : IAnimal, IShippable
{
string ZooName { get; set; }
}
Now let’s implement the interface by the following class:
public class Giraffe : IZooAnimal
{
public string ZooName { get; set; }
public string Size { get; set; }
public string Name { get; set; }
public string LabelText { get; set; }
}
The number of interface properties to implement by the Giraffe class is 5, but due to the implicit implementation, we only need to implement 4 properties. The compiler is able to figure out that the Size property is the implementation of both the IShippable and IAnimal interface.
Now let’s look at the problem. It might look like all is well, but consider the following program:
class Program
{
static void Main(string[] args)
{
Giraffe giraffe = new Giraffe();
giraffe.Name = "Iwana";
giraffe.ZooName = "Artis, Amsterdam, The Netherlands";
giraffe.Size = "2m";
giraffe.LabelText = "Tool cargo";
PrintSize(giraffe);
}
public static void PrintSize(IZooAnimal animal)
{
Console.WriteLine("Animal {0} is {1}", animal.Name, animal.Size);
}
}
It looks great, but this piece of code is not able to compile. The animal.Size will give the following error: Ambiguity between 'Tester.IAnimal.Size' and 'Tester.IShippable.Size'.
Sometimes you want to test if two files are the same. You could run MD5 or SHA hashes of the files, but it might take some time to compute them. A byte by byte comparison might be the fasted. After seeing