Search code examples
c#nullable

How can I safely return a null when an invalid record is found?


I've got this code:

private static QueuedReports GetSingleReportForUnit(string unit, int RptID, DateTime nextExDate)
{
    ReportSchedule rs = ReportSchedulerSQL.GetReportSchedulerRecord(unit, RptID);
    DateTime d8 = new DateTime(0001, 1, 1); //DateTime.Now.AddYears(1);
    if (rs.NextExecution.Date == d8.Date)
    {
        ;// return null; <= I get, "cannot access a closed stream" with this
    }
    QueuedReports qr = new QueuedReports();
    qr.Unit = unit;
    qr.ReportName = GetReportNameForID(RptID);
    List<String> emailAddresses = ReportSchedulerSQL.GetEmailAddressesForUnitRpt(unit, RptID);
    qr.AllEmailAddresses = string.Join(",", emailAddresses.ToArray());
    qr.NextExecution = nextExDate; 
    qr.NextExecutionsBeginDateArg = GetNextExecutionsBeginDateArg(unit, RptID, nextExDate);
    qr.NextExecutionsEndDateArg = GetNextExecutionsEndDateArg(unit, RptID, nextExDate);
    return qr;
}

...which is called from here:

private static IEnumerable<QueuedReports> GetAllFutureReportsForUnit(string unit, int RptID, DateTime finalDate)
{
    List<QueuedReports> listToReturn = new List<QueuedReports>();
    DateTime currentDate = DateTime.Now;
    while (currentDate <= finalDate)
    {
        currentDate = ReportSchedulerConstsAndUtils.GetNextDateForUnitReportAfter(unit, RptID, currentDate);
        var qr = GetSingleReportForUnit(unit, RptID, currentDate);
        listToReturn.Add(qr);
    }
    return listToReturn;
}

If a valid record is found in GetSingleReportForUnit(), that is to say, a "NextExecution" of a value other than "0001, 1, 1", all is well; however, if not, my attempt to return null compiles, but fails at runtime with "cannot access a closed stream"

How can I short-circuit execution of GetSingleReportForUnit() when an invalid date (January 1st of the year 1) inhabits rs.NextExecution?

QueuedReports is a custom class:

public class QueuedReports
{
    public string Unit { get; set; }
    public string ReportName { get; set; }
    public DateTime NextExecution { get; set; }
    public string AllEmailAddresses { get; set; }
    public DateTime NextExecutionsBeginDateArg { get; set; }
    public DateTime NextExecutionsEndDateArg { get; set; }
}

Why would the act of returning null attempt to access a stream? AFAICT, there isn't any stream in this code, so WTH?


Solution

  • This all depends on what rs.NextExecution is doing and how it works. If some sort of stream is being opened in there and it can't return the object that has the Date property on it then your if statement isn't going to work.

    You can use a try catch block to catch whatever exception is being thrown and return null within the catch statement block. You could check if the stream is still valid within that NextExecution object instead of checking the date property if that's available.