So I have a method that does a lookup in an existing List<T>
, populated elsewhere by grabbing the records from a SQL table holding configuration data for each state where we do business. This method just looks up in the list by state abbreviation and then returns the value of a Boolean field in the record.
public bool StateRoundsToQuarterHour(int recordID, string stateAbbrev)
{
bool? result = null;
try
{
// Query our existing list of StateConfig objects for a match, then return the value of RoundMinutes.
result = (from x in listStateConfig
where x.State == stateAbbrev
select x.RoundMinutes).First();
}
catch (Exception e)
{
// if state not found, email error and continue
string strMessage = String.Format("Error: {0} Inner Exception {1}", Convert.ToString(e.Message) + Environment.NewLine, Convert.ToString(e.InnerException));
// log and email error
ErrorContinue(recordID, strMessage);
}
// as long as we found a result, we're happy
if(result != null)
{
return (bool)result;
}
else
{
string strMessage = String.Format("State {0} does not exist in table, but RecordID {1} belongs to that state.", stateAbbrev, recordID);
// log and email error
ErrorContinue(recordID, strMessage);
return false; // if the state doesn't exist, we'll default to rounding is not required
// We send an alert about the state not existing, so we'll be able to act on it
}
}
The List may not contain a result, so in that case the query will not find anything and remain null. I'm not entirely happy with the method using a nullable Boolean internally and then casting it to non-nullable to use in the return, but I don't want the return type of the method to be nullable. Is this a reasonable approach? Where can this be improved?