Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way.
interface IFoo { void DoSomething(); } class Foo : IFoo { #region IFoo Members public void DoSomething() { Console.WriteLine('do something implicitly'); } #endregion #region IFoo Members void IFoo.DoSomething() { Console.WriteLine('do something explicitly'); } #endregion } Foo f = new Foo(); f.DoSomething(); ((IFoo)f).DoSomething();
Above code runs and output
do something implicitly do something explicitly
I believe that this design of C# make inconsistency of behavior. Perhaps it is mandatory that one C# class can inherit from one interface in implicit or expliict way, but not both.
Is there any reason that why C# is designed in such a way?
Your example does not implement IFoo both implicitly and explicitly. You only implement IFoo.DoSometing() explicitly. You have a new method on your class called DoSomething(). It has nothing to do with IFoo.DoSomething, except that it has the same name and parameters.