I have an enum of different States of an user in a Db,
public enum UserState {
ACTIVE = 0,
INACTIVE = 1,
MEMORIAL = 2,
APPLICATION = 3,
}
I need to assign multiple value to each of these states.
I need to assign a URL for redirection, and also a string with the name of the state.
How can I store those 2 values in my enum and get them without having to declare multiple classes or using configuration files?
I tried to use [Description]
Attribute to store one
public enum UserState {
[Description("Active user")]
ACTIVE = 0,
[Description("Inactive user")]
INACTIVE = 1,
[Description("Dead user")]
MEMORIAL = 2,
[Description("Application")]
APPLICATION = 3,
}
And with this I was able to retrieve the name of the state using
public class UserStateExtension{
public static string GetStateName(UserState actualState)
{
DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])actualState
.GetType()
.GetField(actualState.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : string.Empty;
}
}
Is there a method to use a similar trick for the UrlRedirection
?
The usage Of CustomAttributes seems more suitable for the question.
[AttributeUsage(AttributeTargets.Field)]
public class UserAttribute : Attribute
{
private readonly string _urlRedirection;
private readonly string _typeString;
public UserAttribute(string typeString, string urlRedirection)
{
this._typeString = typeString;
this._urlRedirection = urlRedirection;
}
public virtual string UrlRedirection { get { return _urlRedirection; } }
public virtual string TypeString { get { return _typeString; } }
}
By creating a customAttribute like this you are able to have as much parameters as you want. Also it's more readable than having wrongly named Attribute when using the Predefined ones.
This is how the Enum can use it
public enum UserState {
[UserAttribute("Active user", "/user")]
ACTIVE = 0,
[UserAttribute("Inactive user", "/logout")]
INACTIVE = 1,
[UserAttribute("Dead user", "/logout")]
MEMORIAL = 2,
[UserAttribute("Application", "/app")]
APPLICATION = 3,
}
And then to get a specific variable from the Attribute it's like before
public static string GetUrlRedirection(UserState actualState)
{
UserAttribute[] attribute = (UserAttribute[])actualState
.GetType()
.GetField(actualState.ToString())
.GetCustomAttributes(typeof(UserAttribute), false);
return attribute.Length > 0 ? attribute[0].UrlRedirection : string.Empty; // Replace UrlRedirection with the property you want to get
}