Edit: I updated the post to use a Guid
instead of int
. Thanks to those below who have pointed out that using int
doesn't do anything since the base type of the enum is int
.
I have an enum, let's say it's
public enum AnimalType
{
[Animal("00000000000000000000000000000001")]
Bear = 0,
[Animal("00000000000000000000000000000002")]
Cat = 1,
[Animal("00000000000000000000000000000003")]
Dog = 2
}
This enum uses the Animal attribute, defined as:
public class AnimalAttribute : Attribute
{
public AnimalAttribute(Guid id)
{
this.AnimalId = id;
}
public AnimalAttribute(string id)
{
this.AnimalId = new Guid(id);
}
public Guid AnimalId { get; private set; }
// Some more properties
}
As you can see there are two constructors for AnimalAttribute
, allowing to accept the id as a string
or Guid
. The AnimalType
enum uses the string
constructor.
So as of now the enum value can only be accessed by knowing the id. Let's say that if I don't know the id corresponding to a particular enum value, I can also access the enum values using some name/description corresponding to each enum value (probably just "Bear" for Bear, etc.). My question is, how do I set this up so the AnimalAttribute
can accept either the id (and either as a string or a Guid) or the name/description corresponding to the enum value? I would like to make another constructor for AnimalAttribute
like so:
public AnimalAttribute(string name)
{
this.AnimalName = name; // assume there is an AnimalName property.
}
Then I could add another attribute to each enum value like so:
[Animal("00000000000000000000000000000001")]
[Animal("Bear")]
Bear = 0,
And so I could supply either value and I'll be able to get the enum value. The problem with this is that I can't make the constructor in AnimalAttribute
accepting string name
since there is already another constructor accepting string id
. If I can't do that then I thought I could make the constructor with optional parameters. Is there an easy way to set this up?