Lorenzo
Lorenzo

Reputation: 673

recursive function in c# get a parameter

I'm trying to get a parameter with this function...

public static int subsumer(string id,int acc,SqlConnection connection) 
{
    acc++;
    SqlCommand cercas = new SqlCommand("select * from common_relation where id_source ='" + id + "' AND type='@' ", connection);
    SqlDataReader leggsyn = null;
    leggsyn = cercas.ExecuteReader();

    int f = 0;
    while (leggsyn.Read()) 
    {
        f=  subsumer(leggsyn["id_target"].ToString(),acc,connection);
        if (acc <= f) 
        { 
            acc = f; 
        }  
    }

     //siamo arrivati alla fine
    return acc-1;
}

each cycle the parameter acc will increment and debugging i see that in my case it reach value 3, but in the final recursion i get always 0...i can't get it...thank you all

Upvotes: 0

Views: 344

Answers (3)

Guillaume
Guillaume

Reputation: 13138

By returning acc - 1, you are decrementing f returned by your recursive call and I don't think that's what you expect.

public static int subsumer(string id,int acc,SqlConnection connection) 
{
    SqlCommand cercas = new SqlCommand("select * from common_relation where id_source ='" + id + "' AND type='@' ", connection);
    SqlDataReader leggsyn = null;
    leggsyn = cercas.ExecuteReader();

    int f = 0;
    while (leggsyn.Read()) 
    {
        f=  subsumer(leggsyn["id_target"].ToString(),acc + 1,connection);
        if (acc <= f) 
        { 
            acc = f; 
        }  
    }

     //siamo arrivati alla fine
    return acc;
}

On a side note, querying recursively isn't a good design choice. Querying recursively with readers open for each call on the stack is even worse. Not using query parmeters is also a bad thing.

Upvotes: 1

Andy Wiesendanger
Andy Wiesendanger

Reputation: 643

The method increments at the beginning, and decrements at the end, therefore it seems you will always end up at the initial call value of acc (in your case, 0).

Upvotes: 0

Radin Gospodinov
Radin Gospodinov

Reputation: 2323

You need to pass acc by reference. I.e use: public static int subsumer(string id,ref int acc,SqlConnection connection) {

Upvotes: 2

Related Questions