14

When debugging the the following method in a unit test I get the following error

Object reference not set to an instance of an object

when hitting the following line

result = (int)validateDatabase.ExecuteScalar();

The method is

    public static Boolean Validate(string argument1, string argument2)
    {            
        int result = -1;

        using (var connection = new SqlConnection("connection string"))
        {
            SqlCommand validateDatabase = new SqlCommand("PROCEDURE NAME", connection);
            validateDatabase.CommandType = System.Data.CommandType.StoredProcedure;
            validateDatabase.Parameters.Add("@PARAMETER1", System.Data.SqlDbType.NVarChar).Value = argument1;
            validateDatabase.Parameters.Add("@PARAMETER2", System.Data.SqlDbType.NVarChar).Value = argument2; 

            try
            {
                connection.Open();
                result = (int)validateDatabase.ExecuteScalar();
            }
            catch (SqlException exception) { Trace.WriteLine("exception.Message); }
            finally { connection.Close(); }
        }
        return (int)result == 0 ? true : false; 
    }
3
  • 2
    You should have var connection = new SqlConnection(hereComesTheConnectionString) Commented Nov 21, 2013 at 10:07
  • It already is, I made the mistake of using a varialbe name as a place holder name, Ive altered this now Commented Nov 21, 2013 at 10:49
  • having same issue here , after couple of hours testing possibilities thats the only solution works for me : result = validateDatabase.ExecuteScalar() != null ? int.Parse(validateDatabase.ExecuteScalar().ToString()) : 0; Commented Jun 10, 2022 at 17:43

5 Answers 5

15

ExecuteScalar return null if the result set is null according to MSDN. This means that your cast is invalid

See here for the documentation SqlCommand.ExecuteScalar

If you want that cast to work change it to a nullable int

result = (int?)validateDatabase.ExecuteScalar();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks David good shout. If I run my command in the dbms it returns 0 or -1 (representing true or false), but in my code the ExecuteScaler is returning null. Do you know why c# would interpret this as null
@beaumondo according to the documentation it returns The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. So I am assuming your result set is empty.
Nah still not working. In the db query window the result set is never null, always -1 or 0. Like an aggregate function
6

I just experienced a similar problem. What I did was to select an int column from a specific record in a table, but it happened the value of that column is 0. Doing the following caused the exception “Object reference not set to an instance of an object”:

int i = (int)cmd.ExecuteScalar();

My solution was to change the above code to:

int i = 0;
object a = cmd.ExecuteScalar();
if (a != null)
   i = (int)a;

This avoided the exception.

1 Comment

In my case, I was passing a bad value in the where clause parm, causing no rows to be returned. Since ExecuteScalar returns the first column of the first row, then it must return NULL when there are no rows.
4

ExecuteScalar: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Try adding "SELECT CAST(scope_identity() AS int)" at the end of your query.

Comments

0

You are doing it rather wrong - try calling SqlDataReader for validateDatabase.ExecuteScalar() results

1 Comment

The stored procedure only return a single value either -1 or 0. Thats why i wanted to use the ExecuteScalar method
-1
result = validateDatabase.ExecuteScalar();
return result == null ? -1 : (int)result;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.