Reputation: 12367
Let me use medical doctors to explain my question. Now doctors have different fields of specialization, like Neurologist=0,Oncologist=1,Cardiologist=2,Gynecologist=3 etc. Let's say I have a method that takes one of these specialities as an integer and uses it as a parameter to a stored procedure in a database:
DisplaySkills(int speciality)
{
//create a connection to a database, refer to a stored procedure in the database;
//send "speciality" as an argument to that stored procedure
}
Now, here I'm sort of in a dilemma as to whether I should have those specialities inside an enum or declare them seperately. From the first sight it feels like I should go with enums because it's just the case where "one thing can be one of several" but on the other hand it turns out that if I use enums, then I'll have to cast it to get its internal value. Here's an example:
enum Speciality
{
Neurologist=0,
Oncologist=1,
Cardiologist=2,
Gynecologist=3
}
.............
Speciality spec=Speciality.Oncologist;
.............
DisplaySkills(int(spec));
I don't know, maybe having to cast an enum is a perfectly normal practice and is widely used by programmers, but I thought it would impact the performance (no matter noticeably or not)
Upvotes: 1
Views: 148
Reputation: 236218
I'd go with method DisplaySkills
which accepts enum as parameter. Do casting only when call stored procedure.
Because when is see DisplaySkills(int speciality)
then there is no connection with specialties declared in some enum. Maybe I should use it this way?
DisplaySkills(500);
On the other hand:
DisplaySkills(Speciality.Neurologist);
It tells me about all possible parameter values. Also I'd change name to DisplaySkillsOf(Speciality.Cardiologist)
- looks more like English sentence then. And I'd added guard condition to check that passed value contained in Speciality
enum. Otherwise somebody could do this
DisplaySkills((Speciality)500);
And only inside this method you convert passed enum to int when creating parameter (looks like you are using ADO.NET)
cmd.Parameters.Add(new SqlParameter("@Speciality", (int)spec));
One more tip about creating guard for your method. You can use generic enum wrapper to check if appropriate value was passed
if (!Enum<Speciality>.IsDefined(spec))
throw new ArgumentException("spec");
Upvotes: 2
Reputation: 19591
If you are worried about casting then let me tell you it isn't required here you could use this
int value = Speciality.Cardiologist.GetHashCode();
Upvotes: 1
Reputation: 3385
I suggest you to use enum instead of say, static constant class, simply because it is Type safe
.
Rule of a thumb: if you have just Int + string value, use enum. If you have more fields, use static class.
Upvotes: 1
Reputation: 13872
Should I use enums or just seperate constants where I'll need their internal values
In your case I'll choose enum
over constant fields.
maybe having to cast an enum is a perfectly normal practice.
Yes. It is.
Upvotes: 1