title: User-defined conversion operator from base class
body: <p><strong>Introduction</strong></p>
  
  <p>I am aware that "user-defined conversions to or from a base class are not allowed". MSDN gives, as an explanation to this rule, "You do not need this operator."</p>
  
  <p>I do understand that an user-defined conversion <em>to</em> a base class is not needed, as this obviously done implicitly. However, I do need a conversion <em>from</em> a base class.</p>
  
  <p>In my current design, a wrapper of unmanaged code, I use a pointer, stored in an Entity class.
  All the classes using a pointer derive from that Entity class, for example, a Body class.</p>
  
  <p>I therefore have:</p>
  
  <p><strong>Method A</strong></p>
  
  <pre><code>class Entity
  {
      IntPtr Pointer;
  
      Entity(IntPtr pointer)
      {
          this.Pointer = pointer;
      }
  }
  
  class Body : Entity
  {
      Body(IntPtr pointer) : base(pointer) { }
  
      explicit operator Body(Entity e)
      {
          return new Body(e.Pointer);
      }
  }
  </code></pre>
  
  <p>This cast is the illegal one. (Note that I didn't bother writing the accessors).
  Without it, the compiler <em>will</em> allow me to do:</p>
  
  <p><strong>Method B</strong></p>
  
  <pre><code>(Body)myEntity
  ...
  </code></pre>
  
  <p>However, at runtime, I will get an exception saying this cast is impossible.</p>
  
  <p><strong>Conclusion</strong></p>
  
  <p>Therefore here I am, needing an user-defined conversion <em>from</em> a base class, and C# refuses it to me. Using method A, the compiler will complain but the code would logically work at runtime. Using method B, the compiler will not complain but the code will obviously fail at runtime.</p>
  
  <p>What I find strange in this situation is that MSDN tells me I do not need this operator, and the compiler acts <em>as if</em> it was possible implicitly (method B). What am I supposed to do?</p>
  
  <p>I am aware that I can use:</p>
  
  <p><strong>Solution A</strong></p>
  
  <pre><code>class Body : Entity
  {
      Body(IntPtr pointer) : base(pointer) { }
  
      static Body FromEntity(Entity e)
      {
          return new Body(e.Pointer);
      }
  }
  </code></pre>
  
  <p><strong>Solution B</strong></p>
  
  <pre><code>class Body : Entity
  {
      Body(IntPtr pointer) : base(pointer) { }
  
      Body(Entity e) : base(e.Pointer) { }
  }
  </code></pre>
  
  <p><strong>Solution C</strong></p>
  
  <pre><code>class Entity
  {
      IntPtr Pointer;
  
      Entity(IntPtr pointer)
      {
          this.Pointer = pointer;
      }
  
      Body ToBody()
      {
          return new Body(this.Pointer);
      }
  }
  </code></pre>
  
  <p>But honestly, all the syntaxes for these are horrible and should in fact be casts.
  So, any way to make the casts work? Is it a C# design flaw or did I miss a possibility? It's as if C# didn't trust me enough to write my own base-to-child conversion using their cast system.</p>