Reputation: 18684
I would like to have some enums available in my web application. I have a sharedlib type class which has all my DTOs and is referenced by all layers, so I will put it in that project.
I created a .cs file, and added a public enum:
namespace Objects
{
public enum EntityType
{
Thirdparty = 1,
BankAccount = 2
}
}
I have reference data in my SQL table:
I'd like to be able to reference my enums like this:
if(EntityTypeId==Objects.EntityType.BankAccount) ...
However, I can't compare an Int, to an Object.EntityType.
How can this be achieved and a nice clean way? Constants instead?
Upvotes: 2
Views: 98
Reputation: 9124
You can cast between your enum and int values, for example:
EntityType yourEnumValue = (EntityType)yourIntegerValueFromDatabase;
if (yourEnumValue == EntityType.BankAccount) ...
I should point out that if the value of the integer is not valid for your enum you will get an exception thrown. You can either catch this and deal with it (not preferred), or you can use the IsDefined method to test whether the value would work.
if (Enum.IsDefined(typeof(EntityType), yourIntegerValueFromDatabase))
{
yourEnumValue = (EntityType)yourIntegerValueFromDatabase;
}
else
{
// deal with it some other way, perhaps use a default value
}
Upvotes: 3