Search code examples
c#attributeswebget

c# string arguments in attributes


Is it possible somehow to move out the string value declaration in an attribute usage?

Specifically I have:

[WebGet(UriTemplate = "/myResource/{id}")]

But I would rather have something like:

[WebGet(UriTemplate = AStaticDictionaryOrSomething["myResource"])]

The reason is that I want to avoid duplicating the uri values without having to do reflection on the class with the WebGet attribute. So the easiest way I think would be to declare the uri values in a single place, and refer to that from the attribute declaration and from elsewhere.


Solution

  • Declare the strings you need as constants in a new class or somewhere and use those as attribute arguments

    public class ResourceLibrary
    {
         public const string MyResource  = "/myResource/{id}";
    }
    

    And use it like this:

    [WebGet(UriTemplate = ResourceLibrary.MyResource)]