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());
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
In C#, we can also pass a method as a parameter to a different method using a delegate. We use the delegate keyword to define a delegate. Here, Name is the name of the delegate and it is taking parameter. Suppose we have a delegate having int as the parameter.
Create the delegate and matching procedures Create a delegate named MySubDelegate . Declare a class that contains a method with the same signature as the delegate. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.
Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.
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;
}
}
bool DoesItThrowException(Action a)
{
try
{
a();
return false;
}
catch
{
return true;
}
}
DoesItThrowException(delegate { desomething(); });
//or
DoesItThrowException(() => desomething());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With