Interface implementation & casts.

Interface implementation & casts.

I’ve previously blogged about this unusual habit when implementing an interface:

Use explicit interface implementation.

 

      interface I

      {

      void F();

      }

      class C : I

      {

            void I.F()

            {

                  //...

            }

      }

 

I prefer my code to say “Here is where I satisfy the interface’s requirement that I implement method F()”. Otherwise you may think the method is there on its own merit.

The annoying thing about this approach is that it occasionally requires casts. If I have a ‘C’ and I want to call ‘F’ I have to cast. The cast is quite ugly. (Does it also have a perf impact?)

Here’s one way to deal with the problem:

 

      class C : I

      {

            public I I { get { return this; } }

            void I.F()

            {

                  //...

            }

      }

 

      // usage:

      C c = ...;

      c.I.F();

 

Don’t read this as “get the ‘I’ property from ‘c’ and call ‘F()’ on it.”

Read this as “call ‘I.F()’ on ‘c’.” Suddenly it makes perfect sense. The method I wrote was called “I.F()” so the method I call should be “I.F()”.

But there’s a catch. What do I do if the interface is generic?

      interface I<T>

      {

            void F();

      }

      class C<T> : I<T>

      {

            // what's the right name for this property?

            public I<T> I { get { return this; } }

            void I<T>.F()

            {

                  //...

            }

      }

You can’t have generic properties in C#.

I think I will call the property “I_T”. It’s not ideal, but I think I’ll cope.

Got any ideas about how to improve this further?