2

The code example:

public class A{
    public void Check(bool condition){
        Console.WriteLine(???);
    }
    public void Test_1(){
        Check(2 > 3);
    }
    public void Test_2(){
        int x=3;
        Check(x != 6);
    }
}

I need to write to console in method Check not value of parameter condition, but its original expression. For example, when method Test_1 is invoked in program I'd like to see on console "2 > 3". And when method Test_2 is invoked in program I'd like to see on console "x != 6".

  • Pass the expression to a string type parameter in Check method – Adil Mar 02 '15 at 07:39
  • Just as @Adil said, right now Check is only receiving "true" or "false" and that's it. – Dasanko Mar 02 '15 at 07:41
  • 2
    You can pass your condition as a lambda and then use `Expression` to get the body of the lambda to string. – JustSomeGuy Mar 02 '15 at 07:42
  • Side note: check out [Fluent Assertions](https://github.com/dennisdoomen/FluentAssertions) which may be what you are after. – Alexei Levenkov Mar 02 '15 at 07:42
  • This sound like `xy` problem. Why do you need method arguments value ? You can't get method parameter values from reflection. You'd have to use the debugging/profiling API. You can get the parameter names and types, but not the parameters themselves. – Mahesh Mar 02 '15 at 07:43
  • Check out how `INotifyPropertyChanged` is usually implemented http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist using Expressions, that should give you an idea. – JustSomeGuy Mar 02 '15 at 07:58
  • @Onuphrius Tokarev, if you do not want to pass string and want to keep it dynamic, you can use Expression as suggested by others, check my answer for that. – Adil Mar 02 '15 at 10:37

1 Answers1

0

You can use System.Linq.Expressions as a parameter in Check, this will allow you to pass the expression using lambda. Once you have the Lambda Expression you can use LambdaExpression.Body to get the expression in string form.

public static void Check(int n1, int n2, Expression<Func< int, int, bool>> exp)
{
   var compiled = exp.Compile();                      
   Console.WriteLine("Expression: " + exp.Body.ToString() + "\t Result: " + compiled.Invoke(n1,n2)); 
}

public void Test_1(){
    int a = 2, b = 3;
   Check(a,b, (x,y)=>x > y);
}

public void Test_2(){
   int a=3;
   int b=6;
   Check(a,b, (x,y)=> x != y);
}

void Main()
{
    Test_1();
    Test_2();
}

Output

Expression: (x > y)   Result: False 
Expression: (x != y)  Result: True
Adil
  • 146,340
  • 25
  • 209
  • 204