views:

100

answers:

7
public static int ExecuteNonQuery(String procedure, params SqlParameter[] args)
{
    if (args == null) throw new ArgumentNullException("args");
    else
    return ExecuteNonQuery(procedure, new SqlParameter[] { });
}

Why getting recursive function and throwing StackOverFlow Exception when calling this above method.(while the argument contains 5 values)

+3  A: 

That is because overload resolution picks the same ExecuteNonQuery method, so you are essentially calling the same method over and over again.

Your method takes a SqlParameter[] (the params part is just syntactic sugar), and you are calling the same method again, with a SqlParameter[] as the second argument.

driis
A: 

Your args variable is never null; You should to code:

return ExecuteNonQuery(procedure, null);

or to create an overload which doesn't have an args argument.

Rubens Farias
A: 

you need to check if the list has a length of 0, not if it is null. Or you could pass it null, like so:

 public static int ExecuteNonQuery(String procedure, params SqlParameter[] args)
 {
            if (args == null) throw new ArgumentNullException("args");
            else
            return ExecuteNonQuery(procedure, null);
 }
Marius
+1 why was this voted down ?
Brian Agnew
1. `null` doesn't play well with overloading - the call is ambiguous, and the code doesn't compile. 2. let's pretend it compiles, what will it do then? the next `args` will be null, resulting in the exception (but it wouldn't), or `{null}`, resulting in another infinite loop...
Kobi
+6  A: 

Don't confuse an empty array with a null array. You're calling the same method again with an empty array, but the only check you have to cease this function is to check for a null array, and throw an exception. You need something like:

if (args.length == 0) {
   // bail out somehow
}

(after your null check, to prevent NPEs)

Brian Agnew
A: 

Because you call yourself in the return statement.

Aaron Digulla
+1  A: 

The function will recurse infinitely because there is no termination condition: when called with a non-null args parameter it just calls itself with indentical parameters, and there is nothing that stops this infinite recursion other than running out of stack space.

Michael Borgwardt
+1  A: 

Perhaps you wanted something like

public static int ExecuteNonQuery(String procedure, params SqlParameter[] args)
{
  if (args == null) 
      return ExecuteNonQuery(procedure, new SqlParameter[] { });

  // Do some stuff here where args can be assumed != null
}
Doc Brown