Search code examples
expressionvisitor

ExpressionVisitor.VisitParameter, why its printing 2 times each paramter?


Why does VisitParameter print each parameter 2 times?

class MyExpressionVisitor : ExpressionVisitor
    {
        protected override Expression VisitParameter(ParameterExpression node)
        {
            Console.WriteLine(node.Name);
            Console.WriteLine("*************************");
            return base.VisitParameter(node);
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Expression<Func<int,int int>> someExpr = (x,y) => x + y + 1;
            var myVisitor = new MyExpressionVisitor();
            myVisitor.Visit(someExpr);
            Console.ReadKey();
        }
    }

The result:

x


y


x


y



Solution

  • Okay, I got the answer after a lot of checking. The VisitParameter() function returns all the parameters * how much time they are used in the function.

    Expression<Func<int,int int>> someExpr = (x,y) => x + y + 1;
    

    x is used 2 times and y is 1, so it will show the x 2 times and y only ones.