Megajin
Megajin

Reputation: 2768

How to check value of same variable in recursion Method?

I have a variable, which i want to check in a recursive method.

To make it visible:

    private static void myMethod(/*variables*/){
        while (/* condition */) {
            foreach (/* condition */) {
                if (/* condition */) {
                    foreach (/*condition */) {
                        myMethod(/*variables*/);
                            }
                } else {
                /* THIS IS THE PART I AM ASKING FOR:
                 The if statement should ask if the Variable is NOT the same as before.*/

                        if (myMethodVariable != myMethodVariable[from before]){
                        // stuff to do.
}

so myMethodVariable has a value, which is a char/string. I want to check if the value is the same as before, so i can check for duplicates and instantly break the loop.

Is there any way to get the value with like myMethodVariable['index']? Since the variable is a char/string it can not be used like that.

Sorry for my english.

Upvotes: 0

Views: 192

Answers (2)

Orace
Orace

Reputation: 8359

A solution is to store the value given at entry point and then compare it with the new value.

void MyMethod(int pipo)
{
    var oldPipo = pipo;

    //...//
    pipo = SomethingClever();  // Or something with recursive call.
    //...//

    if (oldPipo == pipo)
    {
        // we are done.
    }
}

Upvotes: 2

Thomas Lielacher
Thomas Lielacher

Reputation: 1067

You could pass the variable as argument to the next call:

private static void myMethod(/*variables*/, myMethodVariableFromBefore){
    while (/* condition */) {
        foreach (/* condition */) {
            if (/* condition */) {
                foreach (/*condition */) {
                    myMethod(/*variables*/, myMethodVariable);
                        }
            } else {
            /* THIS IS THE PART I AM ASKING FOR:
             The if statement should ask if the Variable is NOT the same as before.*/

                    if (myMethodVariable != myMethodVariableFromBefore){
                    // stuff to do.
}

Upvotes: 2

Related Questions