tags:

views:

131

answers:

2

I am interested in writing a method that would accept another method as a parameter but do not want to be locked into a specific signature - because I don't care about that. I am only interested whether the method throws an exception when invoked. Is there a construct in the .NET Framework that will allow me to accept any delegate as a parameter?

For example, all of the following calls should work (without using overloads!):

DoesItThrowException(doSomething(arg));
DoesItThrowException(doSomethingElse(arg1, arg2, arg3, arg4, arg5));
DoesItThrowException(doNothing());
+5  A: 

You can't invoke it unless you give it arguments; and you can't give it arguments unless you know the signature. To get around this, I would place that burden on the caller - I would use Action and anon-methods/lambdas, i.e.

DoesItThrowException(FirstMethod); // no args, "as is"
DoesItThrowException(() => SecondMethod(arg)); 
DoesItThrowException(() => ThirdMethod(arg1, arg2, arg3, arg4, arg5));

Otherwise, you can use Delegate and DynamicInvoke, but that is slow and you need to know which args to give it.

public static bool DoesItThrowException(Action action) {
    if (action == null) throw new ArgumentNullException("action");
    try {
        action();
        return false;
    } catch {
        return true;
    }
}
Marc Gravell
With syntax as demonstrated in the question, it's clear that lambda is the only viable choice - he doesn't really want to pass a delegate so much so as a method with all parameters bound.
Pavel Minaev
@Pavel: You will need a 'better' language for that, like Scheme for instance, that allows syntactic abstraction.
leppie
+2  A: 
bool DoesItThrowException(Action a)
{
  try
  {
    a();
    return false;
  }  
  catch
  {
    return true;
  }
}

DoesItThrowException(delegate { desomething(); });

//or

DoesItThrowException(() => desomething());
leppie