Passing the same value in a recursive function?

I have a recursive function with a signature

public static string Recurse(string pattern, ObjectDict dict)

The value dictnever changes. It bothers me that I will have to wrap dozens of links to it and pass it each time I call this function again. Is there any way around this?

By "never changes," I mean after the initial call.

+5
source share
3 answers

The links are extremely light, so don't worry about it.

If you really need to avoid it (and, I think, I don’t think), think about this:

class MyClass
{
    private ObjectDict m_dict;

    public string Recurse(string pattern, ObjectDict dict)
    {
        m_dict = dict;
        return HelperRecurse(pattern);
    }

    private string HelperRecurse(string pattern) 
    {
        // do some work. (referring to m_dict)
        HelperRecurse(pattern);  // Go recursive

        return "Hello World";
    }
}

, , -. static.

+10

- - Recurse. , dict,

public static string Recurse(string initialPattern, ObjectDict dict) {
  Func<string, string> inner = null;
  inner = pattern => {
    // Logic which uses calls to inner for recursion.  Has access to dict
    // because it a lambda.  For example
    if (dict.SomeOperation()) { 
      return inner(someOtherPattern);
    }
    return aValue;
  };
  return inner(initialPattern);
}
+2

, , Recurse ObjectDict, . Recurse(pattern) .

- , . - , , "this", . :)

+1

All Articles