开发者

Code Analysis recommends using const in definition but how in global.asax?

开发者 https://www.devze.com 2023-02-08 03:26 出处:网络
Code public class Global : System.Web.HttpApplication { public开发者_开发百科 const string globalServernameSHA = string.Empty;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消