Search code examples
c#stringfunctiondatareader

Datareader, not all paths returns a value


I want to make a function which returns a string:

public string LienBaseDeConnaissance(string entreprise)
{
    SqlConnection cnx = new SqlConnection("/* connection string */");
    cnx.Open();
    SqlCommand RequeteExiste = new SqlCommand("sp_SEL_LIEN_BASECONNAISSANCE_EXTRANET_CLIENT", cnx);
    RequeteExiste.CommandType = CommandType.StoredProcedure;

    SqlParameter Parameter = RequeteExiste.Parameters.Add("@nom_entreprise", SqlDbType.NVarChar, 15);
    Parameter.Value = entreprise;

    string lienBaseConnaissance;
    SqlDataReader _ReaderLines = RequeteExiste.ExecuteReader();
    while (_ReaderLines.Read())
    {
        if (_ReaderLines["ParStrP1"].ToString() != null)
        {
            lienBaseConnaissance = _ReaderLines["ParStrP1"].ToString();
            return lienBaseConnaissance;
        }
        else
        {
            return null;
        }
    }
    cnx.Close();   
}

I select data thanks to a stored procedure and then I would like to return it as a string. The problem is that if I don't put a return after the while (), all the code doesn't return a value. However I need the variable lienBaseConnaissance which contains the data and out of the while(), the variable in question doesn't have anymore the value I'm looking for.


Solution

  • The problem is the while-loop. It's not an if, so it is possible that the loop is never entered if there are no rows.

    The simplest solution is to assign a default value to the return variable:

    string lienBaseConnaissance = null;
    // .... at the end of the method:
    return lienBaseConnaissance;
    

    Since (i assume that) you are reading a single value this is also possible:

    if(_ReaderLines.Read())
    {
        if (!_ReaderLines.IsDbNull("ParStrP1"))
        {
            lienBaseConnaissance = _ReaderLines.GetString("ParStrP1");
            return lienBaseConnaissance;
        }
        else
        {
            return null;
        }
    }
    else
        return null;
    

    Note that you should also use the using-statement to ensure that unmanaged resources are disposed (e.g. the connection gets closed). Use it for everything that implements IDisposable, so the connection, the command and the reader.