0

I have the following code in my application:

SqlParameter[] sqlCmdParameters=new SqlParameter[0];

Later, I am passing the array to a method as following:

 void CallDB( SqlParameter[] sqlCmdParameters)
 {

       if (sqlCmdParameters == null && sqlCmdParameters.Length>=0 )
       {
           return;
       }   
       Console.Writeline(sqlCmdParameters[0].value);        

  } 

The above code encounters an "Object reference not found exception" as the array is empty. I could perform a element wise null checking in the loop but I think that would not be a good approach. What is the best practice to check for empty array in C#? Also, why an empty array length is 1 when there is no element at all?

1
  • please check my answer and tell me if the bug is gone. Commented Sep 30, 2014 at 2:59

2 Answers 2

2

You should change your if statment

 if (sqlCmdParameters == null || sqlCmdParameters.Length == 0 )
 {
      return;
 }   

In your case you can't never hit the return, because parameters cannot be null and their Length = 0.

Here you have List of SqlParameters.

List<SqlParameter> sqlCmdParameters= new List<SqlParameter>();
SqlParameter param = new SqlParameter();
param.Value = "test";
sqlCmdParameters.Add(param);

If you choose to use List you should check in the if statement

 if (sqlCmdParameters == null || sqlCmdParameters.Count == 0 )
 {
      return;
 }   
Sign up to request clarification or add additional context in comments.

1 Comment

If u just declare a array by the statement
0

Your Code seems to be not proper.

It should be like this.

SqlParameter[] sqlCmdParameters=new SqlParameter[0];    

 void CallDB( SqlParameter[] sqlCmdParameters)
 {

       if (sqlCmdParameters == null || sqlCmdParameters.Length <= 0 )
       {
           return;
       }   
       Console.Writeline(sqlCmdParameters[0].value);        

  } 

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.