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

I am trying to use SqlDataReader to check if a record exists. If it exists, it will return an identifier, otherwise it will return false. When I try to compile, I get the error message “Unable to convert the group of Reading methods to non-delegate type“ bool. ”I am following an example that I found in VB, but it seems that the translation may be incorrect.

 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; } 
+4
source share
4 answers

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

When the compiler sees Read (without parentheses), it thinks you're talking about the method itself, as if trying to assign it to a delegate, say. While what you really want to do is call the method - for this in C # you must specify a list of arguments (which in this case is empty), thus: Read() .

+17
source
 if (rdr.Read()) { strReturn = rdr["ID"].ToString(); } 
+3
source

Function () for calling a method without parameters is optional for C #. Without parentheses, an expression identifies a method (group), not its result value. This behavior makes the grammar much less ambiguous, especially for methods that return delegates.

The first reaction of the programmer to C # when he sees "It is impossible to convert a group of methods ..." into a type without a delegate "...", usually "Oh, I forgot my () to call."

+2
source

Having seen your source, I highly recommend using the using statement for SqlConnection AND SqlDataReader.

If you DO NOT COMPLETE the reader, the garbagecollection moment will decide when the reader will exit. You can bring SqlServer DOWN when you don't know it.

+1
source

Source: https://habr.com/ru/post/1338302/


All Articles