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;
}
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()
.
if (rdr.Read())
{
strReturn = rdr["ID"].ToString();
}
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With