There are several lines in my code that are used as keys for accessing resources. These keys have a specific format, for example.
string key = "ABC123";
Currently, all of these keys are stored as strings, but I would like to make things more reliable and type-safe. Ideally, I would like to verify that the strings are in the correct format at compile time.
The next step is to create the ResourceKey class, which is initialized from the string. Then I can check the format of the string at runtime, for example.
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, @"^[AZ]{3}[0-9]{3}$")); return new ResourceKey () { Key = s }; } }
I would really like you to have some kind of expression about compilation, so that the program could not build if someone is trying to use an invalid key. eg.
ResourceKey k1 = "ABC123"; // compiles ResourceKey k2 = "DEF456"; // compiles ResourceKey k3 = "hello world"; // error at compile time
Is there any way to achieve this?
thanks
roomaroo
source share