Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use enum item name like an attribute parameter

I just want don't use "Managers" for each attribute and use some enum for that.

But it seems it is impossible or I am wrong?

So I try to replace

[RequiresRole("Managers")]

with

[RequiresRole(HardCodedRoles.Managers.ToString())]

...

public enum HardCodedRoles
{ 
            Administrators,
            Managers
}
like image 302
Friend Avatar asked Aug 29 '12 16:08

Friend


People also ask

Can enum have attributes?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

How do I display an enum name?

An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum's element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined.

How to get display name of enum C#?

Let's try our extension method. var status = TransactionStatus. ForApproval; status. GetDisplayName();

Can we assign string value to enum in C#?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.


3 Answers

How about a class instead of an enum, making the class static to avoid somebody new:ing it ?

public static class HardCodedRoles
{
    public const string Managers = "Managers";
    public const string Administrators = "Administrators";
}

[RequiresRole(HardCodedRoles.Managers)] 
like image 66
Tommy Grovnes Avatar answered Oct 16 '22 04:10

Tommy Grovnes


You could also use the nameof keyword, i.e.:

[RequiresRole(nameof(HardCodedRoles.Managers))]
like image 35
regis vaquette Avatar answered Oct 16 '22 05:10

regis vaquette


The reason you see the error is because ToString() is a method and thus the value cannot be calculated at compile time.

If you can use [RequiresRole(HardCodedRoles.Managers)] instead, you can perform the ToString elsewhere in your code, and this could give you the functionality you need. This will require that you change the parameter of your attribute from string to HardCodedRoles.

(I would imagine that using a const won't work, because the type of the parameter will still be string, so the input won't be restricted.)

like image 2
Dan Puzey Avatar answered Oct 16 '22 05:10

Dan Puzey