Cannot convert method group 'Read' to non-delegate type 'bool'

Jason picture Jason · Feb 3, 2011 · Viewed 37.2k times · Source

I am trying to use SqlDataReader to check if a entry exists. If it exists, it will return the ID, else it will return false. When I try to compile, I'm getting the error "Cannot convert method group 'Read' to non-delegate type 'bool'. I have been following an example I found in VB, but it seems the translation may not be correct.

private string checkProfileExists()
{
    string strReturn = "False";
    string strSql = ("SELECT ID FROM tblInformation WHERE txtUsername=@UserName " + 
        "AND TrackingID=@TrackingID");
    string strConn = ConfigurationManager.ConnectionStrings["WEM_PassWord_Reset"].
        ConnectionString;


    SqlConnection objConn = new SqlConnection(strConn);
    SqlCommand objCmd = new SqlCommand(strSql, objConn);

    objCmd.Parameters.AddWithValue("@Username", txtUsername.Text);
    objCmd.Parameters.AddWithValue("@TrackingID", txtTrackingID.Text);

    try
    {
        objConn.Open();
        System.Data.SqlClient.SqlDataReader rdr = objCmd.ExecuteReader();

        if (rdr.Read)
        {
            strReturn = rdr("ID").ToString;
        }
        else
        {
            strReturn = "False";
        }
    }
    catch (Exception ex)
    {
        lblErrorMessage.Text = ex.ToString();
    }
    finally
    {
        objConn.Close();
        objCmd = null;
    }

    return strReturn;
}

Answer

AakashM picture AakashM · Feb 3, 2011

When you see the phrase 'method group' in a C# error, one explanation to consider is that you have omitted the parentheses () from a method that takes no arguments. In this case, the method is Read on your DataReader.

When the compiler sees Read (with no parentheses), it thinks you are talking about the method itself, as if trying to assign it to a delegate, say. Whereas what you actually want to do is invoke the method - to do this, in C#, you must give the list of arguments (which in this case is empty), thus: Read().