6

I've got a recursive function with the signature

public static string Recurse(string pattern, ObjectDict dict)

The value of dict never changes. It kind of bothers me that I should have to carry around dozens of references to it, and pass it around each time I call the function again. Is there a way around this?

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

3 Answers 3

11

references are extremely lightweight, so don't worry about it.

If you really need to avoid it (and, I don't think you do), consider something like 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";
    }
}

By doing this, you are no longer passing around references to the same dictionary, just always accessing a member-object. However, you've lost the static nature of your function now.

Sign up to request clarification or add additional context in comments.

Comments

2

One option is to use a lambda expression to hold the actual logic of the Recurse function. This can then be called recursively and because it's a lambda it will have access to the dict object without having to pass it around

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's a lambda.  For example
    if (dict.SomeOperation()) { 
      return inner(someOtherPattern);
    }
    return aValue;
  };
  return inner(initialPattern);
}

1 Comment

Hah... there was a question about when lambdas are useful on SO recently, and I thought they'd never be useful unless used as a parameter to a function...sure showed me :p Might do it this way. Thanks :D
1

Well, the obvious alternative is to make Recurse an instance method on ObjectDict if you can. Then you can just call Recurse(pattern) internally.

If that's not possible for any reason, don't sweat it. In fact, the two options are really very similar - for instance methods, there's effectively an invisible "this" parameter which is passed along first, before the rest of the parameters. You just happen to have put yours at the other end :)

1 Comment

ObjectDict is just Dictionary<string,object> because I'm too lazy to type that everywhere :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.