title: How to do a static cast in C#?
body: <p>Given a couple types like this:</p>
  
  <pre><code>interface I {}
  class C : I {}
  </code></pre>
  
  <p>How can I do a static type cast? By this I mean: how can I change its type in a way that gets checked at compile time?</p>
  
  <p>In C++ you can do <code>static_cast&lt;I*&gt;(c)</code>. In C# the best I can do is create a temporary variable of the alternate type and try to assign it:</p>
  
  <pre><code>var c = new C();
  I i = c;  // statically checked
  </code></pre>
  
  <p>But this prevents fluent programming. I have to create a new variable just to do the type check. So I've settled on something like this:</p>
  
  <pre><code>class C : I
  {
      public I I { get { return this; } }
  }
  </code></pre>
  
  <p>Now I can statically convert C to I by just calling <code>c.I</code>.</p>
  
  <p>Is there a better way to do this in C#?</p>
  
  <p>(In case anyone's wondering why I want to do this, it's because I use explicit interface implementations, and calling one of those from within another member function requires a cast to the interface type first, otherwise the compiler can't find the method.)</p>
  
  <p>UPDATE</p>
  
  <p>Another option I came up with is an object extension:</p>
  
  <pre><code>public static class ObjectExtensions
  {
      [DebuggerStepThrough]
      public static T StaticTo&lt;T&gt;(this T o)
      {
          return o;
      }
  }
  </code></pre>
  
  <p>So <code>((I)c).Doit()</code> could also be <code>c.StaticTo&lt;I&gt;().Doit()</code>. Hmm...probably will still stick with the simple cast. Figured I'd post this other option anyway.</p>