Using the ConfigurationManager.ConnectionStrings is about the only proper way, to use it properly with sanity check you can have such code:
public DBGateway()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["test"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
throw new Exception("Fatal error: missing connecting string in web.config file");
conString = mySetting.ConnectionString;
}
This will throw useful error in case the connection string is missing, instead of cryptic "null object" error.
Worth to mention that the ConnectionStringSettings class is overriding the ToString() method:
public override string ToString()
{
return this.ConnectionString;
}
So it means that using ConfigurationManager.ConnectionStrings["test"].ToString() is the same like ConfigurationManager.ConnectionStrings["test"].ConnectionString however you still better perform sanity check and personally it looks cleaner to use the actual property and not depend on the class to give it.
answered 2012-09-19T07:41:59.107