Code Analysis recommends using const in definition but how in global.asax?
Code
public class Global : System.Web.HttpApplication
{
public开发者_开发百科 const string globalServernameSHA = string.Empty;
public static string globalSqlConnection = string.Empty;
protected void Application_Start(object sender, EventArgs e)
{
globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
}
These variables should be read just once and definitely should be read only. They have to be available for whole project and therefore should be public.
Is there a way how to define const in code like this ?
Thanks
Declare them as readonly and move initialization to constructor:
public class Global : System.Web.HttpApplication
{
public readonly string globalServernameSHA;
public readonly string globalSqlConnection;
public Global()
{
globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
}
They cannot be declared as const
since the value is retrieved from the settings file. const
values are always hard-coded into the executable program itself.
readonly
is your best bet in the circumstance, which means the variables can only be set in the constructor (the instance or static constructor, depending on how you define the variables), or in a method called by the constructor when the variable is passed as a ref
.
精彩评论