Good day!

To use a variable in enum, it became necessary to translate it into a constant, and therefore faced the following:

public const int Aries = Convert.ToInt32(@"Sample text"); Error 1 The expression being assigned to 'myNameSpace.Class2.Aries' must be constant 

Is there an adequate way to convert text to an int constant?

  • four
    What are you doing?? How do you want to turn Sample text into an int? Even I do not know how to do it, and you want it from the computer! - sp7
  • What are you so - the sum of character codes fit. - smackmychi
  • C # by default does not know how to convert this type of string. The message above implied it. If you want to make the conversion according to your particular logic, then everything is already yours. Implement the logic that suits you. - sp7
  • 1. It depends on what you call the appropriate way. 2. const -variable cannot be initialized by the result of a function call - VladD

2 answers 2

I understand what your problem is - the constant should be constant and be calculated at the compilation stage, and not in the half-time wounds. Correspondingly, it’s just not to put the string :-) Because the function cannot be calculated at the compilation stage, be it Convert.toInt [16 | 32 | 64], int.Parse or whatever.

  • Thanks for the advice! - mabagiri

If the value of a constant cannot be calculated at the compilation stage, then instead of const you can use static readonly :

 public static readonly int Aries = Convert.ToInt32(@"Sample text");