Reputation: 20468
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?
Upvotes: 2
Views: 1394
Reputation: 28809
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.
Upvotes: 2
Reputation: 845
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:
Upvotes: 5
Reputation: 8814
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.
Upvotes: 2