mercredi 6 mai 2015

C# if statement evaluating to true when String.IsNullOrEmpty is false

I have a static method in a helper class that emails administrators to notify them of errors. Before emailing, I check to see if the necessary email addresses have been provided in web.config.

When the first String.IsNullOrEmpty runs, the statement following the if is skipped. However, the statement following the second if executes.

In both cases, I'm able to examine the respective email variable in the Visual Studio debugger, and I can verify that each variable has an actual email address in it. I have also debugged with no watches set, just to ensure that the watches weren't having an effect.

Additionally, I have tried placing { } around each statement that follows an if, but that didn't change the behavior.

If I change the order of these if statements, the same thing occurs; the first throw is skipped, but the second throw executes.

While writing this, I noticed that moving the Console.WriteLine down below the ifs causes everything to work as intended. I'm still curious, though, as to why this would occur if I leave the code as I have posted below. It would be nice to be able to avoid this issue in the future!

public static bool NotifyAdmin(string subject, Exception e, string additionalInfo = "")
{
  String message = String.Format("Exception Message: {0}\n\nStackTrace:\n{1}\n\nAdditional Info:\n{2}", e.Message, e.StackTrace, additionalInfo);

  Console.WriteLine(message);

  String adminEmail = ConfigurationManager.AppSettings["adminEmail"];
  String programEmail = ConfigurationManager.AppSettings["programEmail"];

  // Check to ensure that the necessary app settings have been provided
  if (String.IsNullOrEmpty(adminEmail))
    throw new Exception("adminEmail not specified in AppSettings.");

  if (String.IsNullOrEmpty(programEmail))
    throw new Exception("programEmail not specified in AppSettings.");

  try
  ...
}

Aucun commentaire:

Enregistrer un commentaire