I have a class called Questions
(plural). In this class there is an enum called Question
(singular) which looks like this.
public e
Maybe I missed it, but has anyone tried a simple generic extension method?
This works great for me. You can avoid the type cast in your API this way but ultimately it results in a change type operation. This is a good case for programming Roslyn to have the compiler make a GetValue<T> method for you.
public static void Main()
{
int test = MyCSharpWrapperMethod(TestEnum.Test1);
Debug.Assert(test == 1);
}
public static int MyCSharpWrapperMethod(TestEnum customFlag)
{
return MyCPlusPlusMethod(customFlag.GetValue<int>());
}
public static int MyCPlusPlusMethod(int customFlag)
{
// Pretend you made a PInvoke or COM+ call to C++ method that require an integer
return customFlag;
}
public enum TestEnum
{
Test1 = 1,
Test2 = 2,
Test3 = 3
}
}
public static class EnumExtensions
{
public static T GetValue<T>(this Enum enumeration)
{
T result = default(T);
try
{
result = (T)Convert.ChangeType(enumeration, typeof(T));
}
catch (Exception ex)
{
Debug.Assert(false);
Debug.WriteLine(ex);
}
return result;
}
}
Try this one instead of convert enum to int:
public static class ReturnType
{
public static readonly int Success = 1;
public static readonly int Duplicate = 2;
public static readonly int Error = -1;
}
You should have used Type Casting as we can use in any other language.
If your enum
is like this-
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
And you need to cast to an int
, then do this-
Question q = Question.Role;
.............
.............
int something = (int) q;
In C#, there are two types of casting:
char
->int
->long
->float
->double
double
->float
->long
->int
->char
More can be found in here.
Declare it as a static class having public constants:
public static class Question
{
public const int Role = 2;
public const int ProjectFunding = 3;
public const int TotalEmployee = 4;
public const int NumberOfServers = 5;
public const int TopBusinessConcern = 6;
}
And then you can reference it as Question.Role
, and it always evaluates to an int
or whatever you define it as.
Use:
Question question = Question.Role;
int value = question.GetHashCode();
It will result in value == 2
.
This is only true if the enum fits inside an int
.
Use an extension method instead:
public static class ExtensionMethods
{
public static int IntValue(this Enum argEnum)
{
return Convert.ToInt32(argEnum);
}
}
And the usage is slightly prettier:
var intValue = Question.Role.IntValue();