title: Checking string format at compile time in C#
body: <p>In my code there are several strings which are used as keys to access resources. These keys have a specific format, e.g.</p>
  
  <pre><code>string key = "ABC123";
  </code></pre>
  
  <p>Currently, all these keys are stored as strings, but I'd like to make things more robust and type-safe. Ideally, I'd like to check the strings are in the correct format at compile time.</p>
  
  <p>The next stage is to create a ResourceKey class that is initialised from a string. I can then check the format of the string at runtime, e.g.</p>
  
  <pre><code>ResourceKey key = "ABC123";
  </code></pre>
  
  <p>where ResourceKey is defined as:</p>
  
  <pre><code>using System.Diagnostics;
  using System.Text.RegularExpressions;
  
  class ResourceKey
  {
      public string Key { get; set; }
  
      public static implicit operator ResourceKey (string s)
      {
          Debug.Assert(Regex.IsMatch(s, @"^[A-Z]{3}[0-9]{3}$"));
          return new ResourceKey () { Key = s };
      }
  }
  </code></pre>
  
  <p>What I'd really like to do is to have a sort of compile-time assert so that the program fails to build if anyone tries to use an invalid key. e.g.</p>
  
  <pre><code>ResourceKey k1 = "ABC123"; // compiles
  ResourceKey k2 = "DEF456"; // compiles
  ResourceKey k3 = "hello world"; // error at compile time
  </code></pre>
  
  <p>Is there any way to achieve this?</p>
  
  <p>Thanks</p>