title: Type-proofing primitive .NET value types via custom structs: Is it worth the effort?
body: <p>I'm toying with the idea of making primitive .NET value types more type-safe and more "self-documenting" by wrapping them in custom <code>struct</code>s. However, I'm wondering if it's actually ever worth the effort in real-world software.</p>
  
  <blockquote>
    <p><sup><em>(That "effort" can be seen below: Having to apply the same code pattern again and again. We're declaring <code>struct</code>s and so cannot use inheritance to remove code repetition; and since the overloaded operators must be declared <code>static</code>, they have to be defined for each type separately.)</em></sup></p>
  </blockquote>
  
  <p>Take this (admittedly trivial) example:</p>
  
  <pre><code>struct Area
  {
      public static implicit operator Area(double x) { return new Area(x); }
      public static implicit operator double(Area area) { return area.x; }
  
      private Area(double x) { this.x = x; }
      private readonly double x;
  }
  
  struct Length
  {
      public static implicit operator Length(double x) { return new Length(x); }
      public static implicit operator double(Length length) { return length.x; }
  
      private Length(double x) { this.x = x; }
      private readonly double x;
  }
  </code></pre>
  
  <p>Both <code>Area</code> and <code>Length</code> are basically a <code>double</code>, but augment it with a specific meaning. If you defined a method such as&hellip;</p>
  
  <pre><code>    Area CalculateAreaOfRectangleWith(Length width, Length height)
  </code></pre>
  
  <p>&hellip;it would not be possible to directly pass in an <code>Area</code> by accident. So far so good.</p>
  
  <p><strong>BUT:</strong> You can easily sidestep this apparently improved type safety simply by casting a <code>Area</code> to <code>double</code>, or by temporarily storing an <code>Area</code> in a <code>double</code> variable, and then passing that into the method where a <code>Length</code> is expected:</p>
  
  <pre><code>    Area a = 10.0;
  
      double aWithEvilPowers = a;
      … = CalculateAreaOfRectangleWith( (double)a, aWithEvilPowers );
  </code></pre>
  
  <p><strong>Question:</strong> Does anyone here have experience with extensive use of such custom <code>struct</code> types in real-world / production software? If so:</p>
  
  <ul>
  <li><p>Has the wrapping of primitive value types in custom <code>struct</code>s ever directly resulted in less bugs, or in more maintainable code, or given any other major advantage(s)?</p></li>
  <li><p>Or are the benefits of custom <code>struct</code>s too small for them to be used in practice?</p></li>
  </ul>
  
  <hr>
  
  <p><strong>P.S.:</strong> About 5 years have passed since I asked this question. I'm posting <a href="https://stackoverflow.com/a/39560105/240733">some of my experiences that I've made since then</a> as a separate answer.</p>