Thursday 2 March 2017

Get int value from enum in C#

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.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...