SHARE:

Introducing C# 9: Attributes on local functions

Introduction

Well. It has been a while since I wanted to write this post but I couldn’t find any relevant code example to illustrate it. As you might have guessed C# 9 now allows attributes on local functions (as well as parameter attributes of local functions). To illustrate this I will show you how to use the Conditional attribute to perform conditional local function executions, for example, depending on the environment in which we are running our program. Applying it to local functions can be interesting in this case, however I admit that for the moment it is the only relevant example but it does not matter it is not necessarily the functionality of C# 9 either. more popular now. Finally we will compare with the C# 9 forward to finish our example.

Before C# 9

In this example we’ll see how to execute a local function regarding the execution environment: Let’s consider we are running an action only in DEBUG, we have to run it with the #if preprocessor

We cannot use here the attribute [Conditional(“DEBUG”)] because C# 8 and lower don’ support it on local functions. Too bad! 🙁

With C# 9

Here we are! C# 9 do support attributes on local function, let’s rewrite the previous code using C# 9:

Looks great ! Let’s see now if its works properly :

Debug mode:

Release mode:

Conclusion

As you can see, this feature could be useful, it makes the coder cleaner, but for now I don’t see a lot of use cases for local functions. If you have any interesting REAL LIFE sample for Local functions I will be glad to hear you 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: