Search code examples
c#.netexpression-trees

c# Expression tree: call method with out-parameter?


For example: I want to call the

Int32.TryParse(String numberStr, out Int32 result)

in Expression tree, but I do not know how to get the result of parsing.


Solution

  • You don't need to do anything special to call methods which take out parameters when using Expressions: just treat it as any other parameter, and the runtime takes care of it.

    Here's an example of doing something like:

    void Lambda(string input)
    {
        int parsed;
        int.TryParse(input, out parsed);
        Console.WriteLine("Parsed: {0}", (object)parsed);
    }
    

    using expressions:

    public static void Main()
    {
        var inputParam = Expression.Parameter(typeof(string), "input");
        var parsedVar = Expression.Variable(typeof(int), "parsed");
    
        var tryParseCall = Expression.Call(
            typeof(int),
            "TryParse",
            null,
            inputParam,
            parsedVar); // <-- Here we pass 'parsedVar' as the 'out' parameter
    
        var writeLineCall = Expression.Call(
            typeof(Console),
            "WriteLine",
            null,
            Expression.Constant("Parsed: {0}"),
            Expression.Convert(parsedVar, typeof(object)));
    
        var lambda = Expression.Lambda<Action<string>>(
            Expression.Block(
                new[] { parsedVar },
                tryParseCall,
                writeLineCall),
            inputParam);
    
        var compiled = lambda.Compile();
        compiled("3");
    }
    

    See it working on dotnetfiddle