0

I have existing methods that each returns a String type. And now, I need to return additional value from a method and pass it to the other. I found out that one way to do this is to use the "out parameter".

The value (paramObject) that I want to return is from a method called by the MatchEvaluator delegate.

var result = Regex.Replace(param1, pattern, new MatchEvaluator(m => MethodToMatch(m, param2, out SomeObject paramObject)));

Is this even possible? If not, any workaround or another way to achieve this?

Thanks in advance for any help.

public class TextCompiler
{
    public string Compile(string param1, string param2)
    {
        // some codes here ****

        var pattern = @"@\{.*?}+";

        var result = Regex.Replace(param1, pattern, new MatchEvaluator(m => MethodToMatch(m, param2, out SomeObject paramObject)));

        // OnActionCompleted(paramObject); //the variable raises an error "The name does not exist in the current context."                         

        return result;
    }


    protected string MethodToMatch(Match m, string param2, out SomeObject paramObject)
    {
        // Do something here ****

        var myClass = new MyClass();
        var cmd = "some strings";

        string pm = myClass.Execute(cmd, param2, out SomeObject pObj);

        paramObject = pObj;

        return pm;
    }
}


public class MyClass
{
    public string Execute(string cmd, string param2, out SomeObject paramObject)
    {

        // ** Do something here..

        var pObj = new SomeObject();

        // ** Insert some values to pObj..
        pObj = "some values here";

        var str = "Example Only";

        paramObject = pObj;

        return str;
    }
}
Dale K
  • 25,246
  • 15
  • 42
  • 71
klee
  • 15
  • 1
  • 5

1 Answers1

0

It looks, that you chose invalid architecture. But, you can do it hackly:

        public string Compile(string param1, string param2)
        {
            // some codes here ****

            var pattern = @"@\{.*?}+";

            var objects = new List<Class1>();
            var result = Regex.Replace(param1, pattern, m =>
            {
                var r = MethodToMatch(m, param2, out var paramObject);
                objects.Add(paramObject);
                return r;
            });

            OnActionCompleted(paramObjects);

            return result;
        }

Learn more about closures in .net

Maradik
  • 214
  • 2
  • 8
  • It works, thanks! However, I'm just curious what will be the "valid architecture"? I still need to read about "closures in .Net". I'm still learning.. :) – klee Oct 24 '19 at 10:34