title: Safe & Simple Access to Explicit Interface Members in C#
body: <p>When I am working with explicit interface implementations in C#, it often becomes necessary to cast an object to one of its interfaces in order to access a member of that interface. Because of the improved reliability and maintainability afforded by compile time type checking, I have always preferred to use implicit conversions to perform this. The only way I know of to do this involves two lines of code and introduces another variable into the scope. Below is an example:</p>
  
  <pre><code>public interface IMyType
  {
      string SayHello();
  }
  
  public class MyType : IMyType
  {
      string IMyType.SayHello() { return "Hello!"; }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          var item = new MyType();
  
          // Option 1 - Implicit cast. Compile time checked but takes two lines.
          IMyType item2 = item;
          System.Console.WriteLine(item2.SayHello());
  
          // Option 2 - One line but risks an InvalidCastException at runtime if MyType changes.
          System.Console.WriteLine(((IMyType)item).SayHello());
  
          // Option 3 - One line but risks a NullReferenceException at runtime if MyType changes.
          System.Console.WriteLine((item as IMyType).SayHello());
      }
  }
  </code></pre>
  
  <p>Because the compiler <em>knows</em> that <code>MyType</code> implements <code>IMyType</code> I assume that an implicit cast is better than an explicit one since a later change to the declaration of <code>MyType</code> will result in a compile error instead of an <code>InvalidCastException</code> at runtime. However, I somewhat prefer the simplicity of the explicit cast syntax and have often seen it used in other people's code.</p>
  
  <p>My question is threefold:</p>
  
  <ul>
  <li>Which of the above options do you prefer (and why)?</li>
  <li>Is there a better way to do this?</li>
  <li>What are some best practices regarding performing explicit casts when implicit casts are possible?</li>
  </ul>