Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty readonly Action delegate

Tags:

c#

.net

There are a number of places in our code where () => {} is used (required Action parameter in methods of third-party library).
To make code cleaner I created the following class:

public static class Empty
{
    public static readonly Action Action = () => {};
}

Now it is much nicer:

Alert.Show(title, message, Empty.Action);

The question is may this refactoring cause any problems? I'm sure no but you may know possible side cases. Or may be you know better code improvement here?

like image 808
Sergey Metlov Avatar asked Mar 02 '26 13:03

Sergey Metlov


2 Answers

This change is technically observable: there is always the possibility that some code indirectly compares two new Action(() => {}) instances for equality, and where they would previously not compare equal, they do now.

For an example, if you expose an public event Action X;, you might make sure to initialise it to () => {} to make sure it's never null, and remove any null checks from your code. If you change this to Empty.Action, then malicious code could write X -= Empty.Action;, causing a NullReferenceException in your own code where the event gets invoked.

But in well-written code, the refactoring should not make any difference.

This will not cause any problems, as it is equivalent to defining a static method and referencing it multiple times in your assembly

like image 32
Denis Yarkovoy Avatar answered Mar 05 '26 02:03

Denis Yarkovoy