adem caglin adem caglin - 2 months ago 13
C# Question

How to append attribute property to const values

Consider below code:

[Category("USER")]
public class Permissions
{
public const string Create= "USER-CREATE";

public const string Edit= "USER-EDIT";
.
.
}


I want to remove
USER-
part from const values because i specify it by
Category
attribute. In this case is there a way to get
USER-CREATE
value when i call
Permissions.Create
? If not, how to achieve same functionality with another approach?

Edit

I have to use const values because i will use with attribute.

For example :
[Attribute(Permissions.Create)]


Edit for my real case

New code after @HimBromBeere suggest

[Permissions(Modules.Administration, HomePermissions.Category)]
public class UserPermissions
{
private const string Category = "USER";

private const string Prefix = Modules.Administration + "-" + Category + "-";

public const string Create = Prefix + "CREATE";
public const string Edit = Prefix + "EDIT";
}

Answer

You can define a private const within your Permissions-class which you add to your actual constants.

[Category("USER")]
public class Permissions 
{
    private const string KEYWORD = "USER";

    public const string Create= KEYWORD + "-CREATE";    
    public const string Edit= KEYWORD + "-EDIT";
}

This isn´t exactly what you want but avoids at least some of the duplications. However you still need the "USER" value twice, once within the attribute and once within the private const. Avoiding this would need the attribute to be evaluated which is a runtime-operation and this can´t be used in your scenario.

EDIT: You could even replace the very first line by this:

[Category(Permissions.KEYWORD)]

Now all duplications of the same string are gone.

Comments