Tuesday, January 13, 2009

ConfigurationManager.AppSettings avoid null errors

I found a smart way how to avoid checking for null by using AppSettings.Get or to get an 'Object reference not set to an instance of an object' if not checking for null

Classic method:
string notsmart = String.Empty;
if (ConfigurationManager.AppSettings["test"] != null)
notsmart = ConfigurationManager.AppSettings["test"].ToString();

One-step method:
string keyvalue = ConfigurationManager.AppSettings.Get("test");

No comments: