Can I make a utility method that takes an arbitrary expression as a parameter and calls it?

The exact reasons why I might want to do this is a bit more difficult to enter without sending the code download, but here is an example of one scenario:

try
{
    x.Method(123,"test");
    Assert.Fail("No exception thrown");
}
catch (ApplicationException e)
{
    StringAssert.StartsWith(e.Message, "Oh no!");
}

I would like to reorganize this into something like ... (pseudocode)

TestExceptionMessage({x.Method(123,"test")},"Oh no!");

void TestExceptionMessage(func,string message)
{
    try
    {
        func();
        Assert.Fail("No exception thrown");
    }
    catch (ApplicationException e)
    {
        StringAssert.StartsWith(e.Message, message);
    }
}

I know that C # is quite flexible with lambdas, etc., but does it push it too far or is it reasonably simple?

+4
source share
1 answer

Yes, and that’s pretty straight forward. You can pass a Actiondelegate (or indeed any type of delegate) to a method and call it:

void TestExceptionMessage(Action action, string message)
{
    try
    {
        action();
        Assert.Fail("No exception thrown");
    }
    catch (ApplicationException e)
    {
        StringAssert.StartsWith(e.Message, message);
    }
} 

This delegate can be a reference to a method or it can be a lambda expression as follows:

var x = new MyClass();
TestExceptionMessage(() => x.Method(123, "test"),"Oh no!");

, (, , ), Expression<Action>

void TestExceptionMessage(Expression<Action> expression, string message)
{
    try
    {
        var methodName = (expression.Body as MethodCallExpression)?.Method.Name;
        if (methodName != null) 
        { 
            Debug.WriteLine($"Calling {methodName}");
        }
        expression.Compile().Invoke();
        Assert.Fail("No exception thrown");
    }
    catch (ApplicationException e)
    {
        StringAssert.StartsWith(e.Message, message);
    }
} 

:

var x = new MyClass();
TestExceptionMessage(() => x.Method(123, "test"),"Oh no!");
+6

All Articles