In my code there are several strings which are used as keys to access resources. These keys have a specific format, e.g.
string key = "ABC123";
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.
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.
ResourceKey key = "ABC123";
where ResourceKey is defined as:
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 };
}
}
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.
ResourceKey k1 = "ABC123"; // compiles
ResourceKey k2 = "DEF456"; // compiles
ResourceKey k3 = "hello world"; // error at compile time
Is there any way to achieve this?
Thanks