How can I require a delegate to be static?
05:23 27 May 2026

In some situations where I write a method that accepts a delegate as a parameter I find the need to require that the passed delegate must be static.

Here is an example that can serve as a working scenario for the purposes of this question:

Say, I want to write a truly thread-safe replacement for RunTask( action ).

The replacement could look like this:

//executes asyncDelegate in a different thread to process an instance of P and
//produce an instance of R, then executes resultConsumer in the original thread,
//to process R.
RunTask( P parameter, System.Action asyncDelegate,
        System.Action resultConsumer )

To make this truly thread safe, I need to ensure that P and R are immutable, (I got this, (yes, believe me, I got this,)) and then I also need to ensure that asyncDelegate is free from side-effects.

To ensure that asyncDelegate is free from side-effects, I need to achieve one of the following:

  • Either ensure that asyncDelegate is static, or

  • Somehow obtain the instance that asyncDelegate operates on. (So as to ensure that it, too, is immutable.)

So, does anyone know of any way in which I can achieve any of that? A compile-time solution would be great, a runtime assertion solution would also work.

Note that there exist other scenarios too, where I need to require a static delegate, for example in any situation where bugs could be caused by capture-at-lambda-creation-time. However, such scenarios would be more complicated to describe here.

c# lambda static delegates side-effects