Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking string format at compile time in C#

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

like image 723
roomaroo Avatar asked Feb 03 '09 12:02

roomaroo


3 Answers

You could check the values with a unit test. One of my co-workers had to do something similar to this in a project where we needed to ensure that all classes in a certain namespace had certain attributes applied to them.

Run the unit tests with your build (you do that anyways right? :) or as part of an integration build. This will keep your source cleaner as well as you won't have to introduce code that does assertions.

like image 150
Andrew Hare Avatar answered Nov 05 '22 21:11

Andrew Hare


I believe that I would add a Settings class and store them there instead of creating a new type. The Settings class can be backed by an application configuration file that will make them easier to change via configuration file changes if needed. If you don't specify them in the configuration file, though, it will use the values you set as defaults.

I'd also go the unit test route. You'll need to use the InternalsVisibleTo attribute in your Assembly.cs file since I don't think that Settings can be used outside the project if you don't.

like image 2
tvanfosson Avatar answered Nov 05 '22 21:11

tvanfosson


Do you really want these keys hardcoded into your app? Wouldn't it be better to have them in a config file? Then if there are any problems post compile, it's simply a runtime configuration issue.

like image 1
Adam Ralph Avatar answered Nov 05 '22 21:11

Adam Ralph