Unexpected Nuance with C# Interfaces

February 5th, 2007

I recently read about how you can implement an interface either implicitly or explicitly. I have always used the implicit declaration without knowing the difference. The explicit declaration causes it to be masked from the instances of the implementation class. If you cast the implementation to the interface you can access the explicitly declared interface methods. In a way it acts like a access modifier like the public, private and protected.

In the code sample below I have created an IDog interface which can Bark, Run and Catch. And then I have 2 classes which implement it, Terrier and BullDog. The BullDog class explicitly declares the Run method. And as you can see in the screenshot to the right the Run is not available from Intellisense.

But when you cast the BullDog to IDog you can reach all of the methods. I believe I have seen this before and could not explain it. It is a very unexpected behavior, but I can see how it could be useful. What I would prefer is a variation of how this works.

The variation I have in mind would be applied to typed DataSets. When a typed DataSet generates the DataSet, DataTable and DataRow classes it adds many methods and none of them are directly related to the domain they are supposed to represent. On a DataRow I would rather call product.Price than row["Price"] and take advantage of compile-time protection. I have taken advantage of the fact that a typed DataSet is a partial class and have added my own methods but it is a lot of manual work. It would be quite helpful if the generated DataSet made use of an interface based on a domain specific template and then only expose the methods which make sense while allowing the databound controls to make use of all of the existing features on the DataSet. I believe this could all be done with existing language features but the code generator would have to be updated to read the interface templates and carry it out in the generated code.

Below is the code for the IDog example shown in the screenshots.


2 Responses to “Unexpected Nuance with C# Interfaces”

  1. BrianDeacon Says:

    Hey Brennan,
    I took a look at this in Reflector, and it explains what's going on, but the answer is even weirder. Check out my post and you'll see what I'm talking about. Bulldog.Bark() is private. Strange.

    Anywho: http://devdeacon.blogspot.com/2007/02/yet-weirder-nuances-with-c-interfaces.html

  2. Brennan’s Blog » Blog Archive » Reasons to Blog and Tips to do it Well Says:

    [...] XML and C# code and Paint.NET to crop screenshots. The result looks like the entry I wrote on a funky language feature in C#. Getting your point across visually helps your readers and makes for a much more colorful [...]