I have a class called Questions
(plural). In this class there is an enum called Question
(singular) which looks like this.
public e
Question question = Question.Role;
int value = (int) question;
Will result in value == 2
.
To ensure an enum value exists and then parse it, you can also do the following.
// Fake Day of Week
string strDOWFake = "SuperDay";
// Real Day of Week
string strDOWReal = "Friday";
// Will hold which ever is the real DOW.
DayOfWeek enmDOW;
// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
// This will never be reached since "SuperDay"
// doesn't exist in the DayOfWeek enumeration.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
// This will parse the string into it's corresponding DOW enum object.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}
// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");
The easiest solution I can think of is overloading the Get(int)
method like this:
[modifiers] Questions Get(Question q)
{
return Get((int)q);
}
where [modifiers]
can generally be same as for the Get(int)
method. If you can't edit the Questions
class or for some reason don't want to, you can overload the method by writing an extension:
public static class Extensions
{
public static Questions Get(this Questions qs, Question q)
{
return qs.Get((int)q);
}
}
In Visual Basic, it should be:
Public Enum Question
Role = 2
ProjectFunding = 3
TotalEmployee = 4
NumberOfServers = 5
TopBusinessConcern = 6
End Enum
Private value As Integer = CInt(Question.Role)
int number = Question.Role.GetHashCode();
number
should have the value 2
.
public enum QuestionType
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
...is a fine declaration.
You do have to cast the result to int like so:
int Question = (int)QuestionType.Role
Otherwise, the type is still QuestionType
.
This level of strictness is the C# way.
One alternative is to use a class declaration instead:
public class QuestionType
{
public static int Role = 2,
public static int ProjectFunding = 3,
public static int TotalEmployee = 4,
public static int NumberOfServers = 5,
public static int TopBusinessConcern = 6
}
It's less elegant to declare, but you don't need to cast it in code:
int Question = QuestionType.Role
Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.