2

Here is my class :

namespace My.Core
{
    public static class Constants
    {
        public const string Layer_ver_const = "23";

        public const string apiHash_const = "111111";
    }
}

Now i want to set conditional value for apiHash_const.
Mean :

if(Layer_ver_const == "23")
{
  apiHash_const = "111111";
}
else if(Layer_ver_const == "50")
{
  apiHash_const = "222222";
}
else
{
  apiHash_const = "333333";
}

How can i do that?

SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 6
    If `Layer_ver_const` is a constant then how would any of your other values ever be set? – Charles Mager May 21 '16 at 17:49
  • I have many Hash_codes. I want to change version manually in calss and this class return desire Hash_code. – SilverLight May 21 '16 at 17:51
  • 3
    Sounds like you should simply change your 'derived' constants to `static readonly` and set them in the static constructor. – Charles Mager May 21 '16 at 17:57
  • I think @CharlesMager is right. I'm pretty sure the `const` keyword means it is a compile time constant and cannot be set programatically. – DevNoob May 21 '16 at 17:59

3 Answers3

5

I'm afraid that you can't do that at runtime. But you can always change the constant keyword to static or static readonly and this code will work.

public static class Constants
{
    public const string Layer_ver_const = "23";

    public static readonly string apiHash_const;

    static Constants()
    {
       if(Layer_ver_const == "23")
       {
         apiHash_const = "111111";
       }
       else if(Layer_ver_const == "50")
       {
         apiHash_const = "222222";
       }
       else
       {
         apiHash_const = "333333";
       }
    }
}

If you want to know the difference between constant and static readonly checkout this link:

Static readonly vs const

Community
  • 1
  • 1
Mateusz Myślak
  • 775
  • 6
  • 16
2

I would recommend turning these to a readonly field, and set them inside the constructor

Constants are a different beast. Once a constant is declared in a project, every other project referencing it will retain the value of the constant until you rebuild the projects. Thus, changing a constant is not what you want to do.

Make these readonly , and inside the constructor set them.

AlbertGarde
  • 369
  • 1
  • 13
Ryan Ternier
  • 8,714
  • 4
  • 46
  • 69
2

As other answers have specified, you probably want a readonly field instead. You could even use a property. Nevertheless, it is possible to have the field const, by making the entire expression that calculates it a constant expression:

public const string Layer_ver_const = "23";
public const string apiHash_const = 
    Layer_ver_const == "23" ? "111111" :
    Layer_ver_const == "50" ? "222222" :
    "333333"
;

This is possible only because we can construct a simple expression to assign apiHash_const. In more complicated scenarios you'll have to settle for a readonly field.

Jeroen Mostert
  • 27,176
  • 2
  • 52
  • 85