Best way to define constant in asp.net

Which of below 2 method is better to declare constant/config driven variables in asp.net from coding standing perspective, from architecture perspective.

Type1-

class Constants
{
    public static string ConnectionString
    {
        get
        {
            //Get the connection string value from web.config
            if (ConfigurationManager.AppSettings["ConnectionString"] != null)
            {
                return ConfigurationManager.AppSettings["ConnectionString"];
            }
            else
            {
                return string.Empty;
            }
        }
    }
}

Type 2-

class Constants
{
    public static string ConnectionString = ConfigurationManager.AppSettings["ConnectionString"] != null ?
                                                ConfigurationManager.AppSettings["ConnectionString"] : string.Empty;
}

Is there any better way to do? Is it better to use property or use a public variable?

Jon Skeet
people
quotationmark

Firstly, the null-coalescing operator makes this a lot simpler.

Next, assuming ConfigurationManager.AppSetting["ConnectionString"] doesn't change over time, you could use:

// TODO: Rename this...
class Constants 
{
    private static readonly string connectionString;
    public static string ConnectionString { get { return connectionString; } }

    static Constants()
    {
        ConnectionString = ConfigurationManager.AppSettings["ConnectionString"] ?? "";
    }
}

Or just use a property fetching it every time - a simpler version of your first code:

// TODO: Rename this...
class Constants 
{
    public static string ConnectionString
    {
         get { return ConfigurationManager.AppSettings["ConnectionString"] ?? ""; }
    }
}

With C# 6 the property is even slicker:

// TODO: Rename this...
class Constants 
{
    public static string ConnectionString =>
        ConfigurationManager.AppSettings["ConnectionString"] ?? "";
}

The choice of whether to evaluate the ConfigurationManager.AppSettings["ConnectionString"] expression or to use a cached field is unlikely to make much difference - but I would recommend using a property instead of a public field, as that means you can change the implementation later (e.g. to change its laziness) with no worries about backward compatibility.

people

See more on this question at Stackoverflow