Home > Software engineering >  Is it possible to express that a result may be null/may not be null depending on a Boolean parameter
Is it possible to express that a result may be null/may not be null depending on a Boolean parameter

Time:06-04

In C#, is it possible to express that a result may be null/may not be null depending on a Boolean parameter, something like the following (not compiling) code?

[Version 2 with Jeroen's suggestions in regards to SingleOrDefault() applied]

    [return: NotNullWhen(true, "noRowsThrows")]
    public DataRow? ExecuteToDataRow(SqlCommand command, bool noRowsThrows) {
        DataTable dataTable = ExecuteToDataTable(command);
        DataRow? result = dataTable.Rows.Cast<DataRow>().SingleOrDefault();
        if ((result is null) && noRowsThrows) throw new ArgumentException($"The command did not return any rows!");
        return result;
    }

CodePudding user response:

Thank you, I go for @Jeroen's first suggestion:

    public DataRow ExecuteToDataRow(SqlCommand command) {
        DataRow? result = ExecuteToDataRowOrNull(command);
        if (result is null) throw new ArgumentException($"The command did not return any rows!");
        return result;
    }

    public DataRow? ExecuteToDataRowOrNull(SqlCommand command) {
        DataTable dataTable = ExecuteToDataTable(command);
        return dataTable.Rows.Cast<DataRow>().SingleOrDefault();
    }

The later suggestion with Execute... ?? throw new MoreAppropriateExceptionInContext() is IMHO undesirable as then the caller has to care about the exception details which are going to be different with every call and then tend not to be as complete (the message of this example is of course also not very helpful but is in the sense of a minimal reproducible example, the production code would include the query text and map the InvalidOperationException back to an ArgumentException).

CodePudding user response:

I would try something like this:

bool someBooleanVariable = true;

object? someObject = new Object(/*blah blah blah*/);

object? result = someBooleanVariable? (someObject ?? new Object()) : someObject;
  • Related