Wrapping StopWatch timing with a delegate or lambda?

I’m writing code like this, doing a little quick and dirty timing:

Surely there’s a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

I know it can be done as a Delegate but I’m wondering about the lambda way.

Add Comment
1 Answer(s)

You could try writing an extension method for whatever class you’re using (or any base class).

I would have the call look like:

Then the extension method:

Any object deriving from DependencyObject can now call TimedFor(..). The function can easily be adjusted to provide return values via ref params.

If you didn’t want the functionality to be tied to any class / object you could do something like:

Then you could use it like:

Failing that, this answer looks like it has some decent “generic” ability:

Wrapping StopWatch timing with a delegate or lambda?

Answered on April 6, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.