Restrict method parameter of string type to const field from one given class

432 views Asked by At

Let's say we have some method

public class SomeClass 
{
    public Sth GetByKey(string key) 
    {
        //not important
    }
}

static class SomeKeys
{
    public static string Abc = "Abc";
    public static string Xyz = "Xyz";
}

and it can't by changed. Is there a relatively easy way to restrict values passed to this method to fields from class SomeKeys in some projects? So a.GetByKey("Qwerty") and a.GetByKey("Abc") would generate some warning or error and a.GetByKey(SomeKeys.Abc) wouldn't.

I know it's a bad design and so on and I don't search for a way to refactor this. Right now I'm mostly curious if it is possible. I was thinking about writing some postsharp magic but i don't know if it's worth the trouble. It could show error during compilation or it may be some magic rule in resharper or something else completely.

Edit
Also i don't want to change calls to GetByKey, parameter type must be a string.

1

There are 1 answers

3
Simon Luckenuik On

No refactoring or change needed to the original class, simply create a wrapper class over SomeClass (NewSomeClass) that takes care of being strongly typed, start using NewSomeClass everywhere. Way easier than implementing some Roslyn/Resharper trick that you would need to deploy to your whole team.

public class NewSomeClass 
{
    private SomeClass inner;

    private NewSomeClass(SomeClass inner)
    {
      this.inner = inner;
    }

    public Sth GetByKey(SomeKey key) 
    {
        return this.inner.GetByKey(key.Value);
    }
}

public sealed class SomeKey
{    
   SomeKey(string val)
   {
      this.Value = val;
   }
   public string Value {get;}

   public static readonly SomeKey Abc = new SomeKey("Abc");

   public static readonly SomeKey Xyz = new SomeKey("Xyz");
}