Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function returning a const value

I have a following function which accepts a enum value and based upon the enum value returns a constant value(which is in a different class). Now i get a "Constant initializer missing" Error.

public const int Testfunction(TESTENUM TestEnum)
{
    switch(TestEnum)
    {
      case TestEnum.testval1:
         return testclass.constvalue;
      case TestEnum.testVal2:
         return testclass.constvalue1;
      case TestEnum.testVal3:
         return testclass.constvalue2;
    }
}
  1. how exactly the function's return type would be? (I am using object return type and this does not throw any error)

  2. Is there any other option to achieve the same?

like image 281
now he who must not be named. Avatar asked Nov 27 '22 03:11

now he who must not be named.


2 Answers

What's happening here is the compiler thinks that you are trying to declare a public constant integer field named Testfunction, and is extremely surprised to discover that there is no = 123; following the identifier. It's telling you that it expected the initializer.

There are a number of places in the C# compiler where the development team anticipated that C and C++ users would use a common C/C++ syntax erroneously. For example, there's a special error message for int x[]; that points out that you probably meant int[] x;. This is an example of another place where the compiler could benefit from a special-purpose error message that detects the common mistake and describes how to fix it. You might consider requesting that feature if you think it's a good one.

More generally, "const" in C# means something different than it means in C or C++. C# does not have the notion of a "const function" that does not mutate state, or a "const reference" that provides a read-only view of potentially-mutable data. In C# "const" is only used to declare that a field (or local) is to be treated as a compile-time constant. (And "readonly" is used to declare that a field is to be written only in the constructor, which is also quite useful.)

like image 136
Eric Lippert Avatar answered Nov 29 '22 16:11

Eric Lippert


Removing "const" keyword from your function return type should solve the problem

It should be like this

public int Testfunction(TESTENUM TestEnum)
{
    ...

Return type cannot be declared constant

like image 42
Pawan Nogariya Avatar answered Nov 29 '22 17:11

Pawan Nogariya