Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a web.config key value pair be used as a compile time constant in asp.net c#?

I am trying to do this below, is there a way to do this or are web.configs only available at run-time, because I am getting a red line error saying must be compile time constant?

AppSettings:

  <add key="MyString" value="TheValueOfTheString"/>

Code:

   public const string MyString = ConfigurationManager.AppSettings["MyString"];
like image 406
Rayshawn Avatar asked Nov 28 '12 15:11

Rayshawn


1 Answers

the problem is the use of const. const means the value is hard coded at design time.

const string MyString = "the text...";

an appsettings value is not known until runtime so it's not a constant value. instead you can use a static readonly value

static readonly MyString = ConfigurationManager.AppSettings["MyString"];

the difference is how the value is interpereted at compile time. when a constant is used the actual value is referenced, not the variable MyString. a static readonly value is compiled as the variable.

like image 68
Jason Meckley Avatar answered Sep 28 '22 16:09

Jason Meckley