Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 327
Jason Avatar asked Feb 03 '11 18:02

Jason


3 Answers

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().

like image 62
AakashM Avatar answered Nov 01 '22 06:11

AakashM


if (rdr.Read())
{
    strReturn = rdr["ID"].ToString();
}
like image 3
mqp Avatar answered Nov 01 '22 08:11

mqp


The () for method invocation of parameterless methods are not optional in C#. Without the parentheses the the expression identifies the method(group) and not its result value. This behavior makes the grammar much less ambiguous, especially for methods that return delegates.

The first reaction of a C# programmer when he sees "Cannot convert method group '...' to non-delegate type '...'" is usually "Oh I forgot my () for invocation".

like image 3
CodesInChaos Avatar answered Nov 01 '22 06:11

CodesInChaos