Enums and casting

D

DKode

I started using Enums to make my code more readable. Here is my ENUM:

public enum EntryType : int {
RegularHours = 1,
Lunch = 2,
Vacation = 3,
Sick = 4,
Personal = 5
}

When I am testing against this enum in code I do the following:

if((int)dr["TypeID"] == (int)EntryType.RegularHours) {
// do something
}

Is it always required for me to cast the Enum to int, even though I
already have that set in the enum declaration? otherwise I get a
compile error about not being able to use the '==' operator against int
and EntryType enum

thanks

Sean
 
M

Mythran

DKode said:
I started using Enums to make my code more readable. Here is my ENUM:

public enum EntryType : int {
RegularHours = 1,
Lunch = 2,
Vacation = 3,
Sick = 4,
Personal = 5
}

When I am testing against this enum in code I do the following:

if((int)dr["TypeID"] == (int)EntryType.RegularHours) {
// do something
}

Is it always required for me to cast the Enum to int, even though I
already have that set in the enum declaration? otherwise I get a
compile error about not being able to use the '==' operator against int
and EntryType enum

thanks

Sean

Because I'm anal retentive, I tend to do the following:

EntryType typeID = (EntryType) dr["TypeID"];

if (typeID == EntryType.RegularHours) {
// do something
}

Doesn't answer your question, as I haven't the time to do some testing to
figure it out (can't remember stuff like this off top of my head). Hope it
helps.

:)

Mythran
 
D

DKode

I tried casting the field to the Enum and got the same exception.

thought there was an easier way of doing it. oh well

thanks
 
O

Ole Hanson

You have the enums already - why not create the enum from the datareader?
EntryType t = Enum.Parse(typeof(EntryType), dr["TypeID"], true);

if(t == EntityType.RegularHours)
{
stuff...
}

etc.


/Ole
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top