Preventing simple errors with the null coalescing operator

How often have you seen code like this?

   1:  string myAppSetting = ConfigurationManager.AppSetting["key"];
   2:  if(myAppSetting==null)
   3:       myAppSetting = "MyDefaultSetting"

Or worse yet not even do the check, then during the deploy process the appsetting doesn't get copied over to the instance and you get a null reference exception. That is not a good look.

That sucks. But is preventable in code. That's when the null coalescing operator(??) comes in handy.

Example:

   1:  string myAppSetting = 
   2:            ConfigurationManager.AppSetting["key"] ?? "MyDefaultSetting"
And that's it. A very easy way to prevent errors after deployment. Of course it's useful in other scenarios as well
 
Now the story in VB isn't nearly as nice
 
   1:  Dim myAppSetting As String = IIf(ConfigurationManager.AppSetting("key") Is Nothing, _
   2:  "MyDefaultSetting", ConfigurationManager.AppSetting("key"))
There is a gotcha with IIF as well because it's a function and not a language feature.
 
Anytime you can code to prevent error's  and keep the application working it's a win. Of course make note that the default value you set could cause other errors so use appropriately.

No Comments