title: Abstraction hindering use of custom types, what are the rules to follow in an implementation?
body: <p>I have built a custom typesystem for usage in C# scripting inside an application. The scripts are compiled on-the-fly and allow interaction with the application internal data. This typesystem is designed in an abstract way using interfaces like <code>IValue</code>. Implementation of <code>IValue</code> can be a <code>RefString</code>, <code>RefInteger</code>, <code>RefDouble</code> (among many others, but this is sufficient for demonstrating my issue).</p>
  
  <p>Now we come to the point where I get stuck... The use of these <code>IValue</code> objects is somewhat unnatural. It is considered as a good design to always use the interfaces to interact with the objects but there is no possibility to define an implicit conversion or overloading an operator for interfaces. This yields to situations where ugly explicit casting is unavoidable so that the right operator gets used.</p>
  
  <p>Example:</p>
  
  <pre><code>IValue Add(IValue a, IValue b)
  {
      //return a+b; // won't work: which operator +() to use?
      return (RefInteger)a + (RefInteger)b;
  }
  </code></pre>
  
  <p>In the case of C# in expressions involving value types, implicit conversions are provided. What is a good way to design such a custom system?</p>
  
  <p>I rewrote the typesystem removing the <code>IValue</code> interface and introducing a <code>RefValue</code> base class. This way already a part of the explicit casts could be eliminated. I implemented some of the operator overloading in this base class but that caused a lot of trouble with the default conversion operators... Beside this the logic to implement in the operator implementation implicates a lot of knowledge about the types in the system. I think this is somehow still the way that one must go but what are the rules to follow, to implement this in a good and safe way?</p>
  
  <p><strong>EDIT</strong>: After struggling a while, some of the rules I could find out are:</p>
  
  <ul>
  <li>Declare implicit only the conversion operators from base-types (int, double, string, ...)</li>
  <li>Declare explicit the conversions to base-types (to avoid implicit casts to int!! what happens quite often, but why?)</li>
  <li>To avoid ambiguous calls the +, -, /, * operators should not be overridden in the base class and in the derived classes. [What is the way to go then? I did the operation overloading in the derived classes, this requires casting on use, which is again ugly...]</li>
  </ul>