In an ASP.NET MVC app, I have code that boils down to the following:
public ActionResult Test() {
string query;
try {
query = GenerateQueryString();
}
catch (Exception ex) {
ModelState.AddModelError("error", ex.Message);
}
... do additional validation ...
if (ModelState.IsValid) {
return RedirectToAction("Success?" + query);
}
return View(); // Show validation messages
}
The above code has a compile error … query might not be initialized.
However, the logic in the code will clearly initialize query before using it.
What is the best way to resolve this issue?
The C# compiler is looking at your code and seeing that the value of the variable is initialized in a
tryblock and is then used later on. It can see that a logical branch of execution exists where an exception is thrown, is caught, and then the subsequent code is executed with an uninitialized value.The simplest way to stifle the error is to assign a default value to the field.
nullis sufficient. As you’re adding the error to the MVC model state and are checking that value later on before accessingquery, you shouldn’t be in a situation when the default value will matter.