user2621858
user2621858

Reputation: 121

Checking an empty object array in C#

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?

Upvotes: 0

Views: 2571

Answers (2)

jadavparesh06
jadavparesh06

Reputation: 946

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);        

  } 

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

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;
 }   

Upvotes: 2

Related Questions