Most likely working code:
public static class TestClass { public const int constValue1 = 1; public const int constValue2 = 2; public const int constValue3 = 3; } enum TestEnum { testVal1, testVal2, testVal3 } public int TestFunction(TestEnum testEnum) { switch (testEnum) { case TestEnum.testVal1: return TestClass.constValue1; case TestEnum.testVal2: return TestClass.constValue2; case TestEnum.testVal3: return TestClass.constValue3; } return 0;
First, according to const (C # link) :
The const keyword is used to change the declaration of a field or local variable. It indicates that the value of a field or local variable is constant, which means that it cannot be changed.
In C #, const is only used as a field modifier (e.g. TestClass.constValue1 ) or a local variable, not suitable for the return type of a function.
So, you are from the great kingdom of C / C ++. Thinking with my very limited knowledge of C / C ++, the returned const types in C / C ++ only make sense with pointers ...
But if you use unsafe code, there is no pointer to C # . There are only value types (e.g. int / DateTime / TestEnum / structs) and reference types (e.g. string / classes). There is more to read on the Internet.
Since int is a value type in C #, when you return it, it gets copied . Therefore, even if you return an int constant, the return value is not a constant, and changing the return value will not "change the constant and call SegFault".
Ok, I forgot to answer your questions ...
How exactly will the function type be returned? (I use the return type of the object and this does not cause any error)
As shown in the above code, int .
const int blah = 1 declares only a variable / field of blah type int , which it should not change (by making blah = 2 ). In C #, const int not a type.
Is there any other option to achieve the same?
Well ... I guess I really don't need to answer this question ...
source share