7

Introducing C# 9: Attributes on local functions

 3 years ago
source link: https://anthonygiretti.com/2020/10/19/introducing-c-9-attributes-on-local-functions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introducing C# 9: Attributes on local functions

2020-10-19 by anthonygiretti

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

using System; using System.Diagnostics;

namespace CSharp9Demo { class Program { static void Main(string[] args) { static void DoAction() { // Perform action Console.WriteLine("Performing action"); }

#if DEBUG DoAction(); #endif } } }

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:

using System; using System.Diagnostics;

namespace CSharp9Demo { class Program { static void Main(string[] args) { [Conditional("DEBUG")] static void DoAction() { // Perform action

Console.WriteLine("Performing action"); }

DoAction(); } } }

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

Debug mode:

localattribute-perform-action2.png?resize=631%2C124&ssl=1

Release mode:

localattribute-not-perform-action2.png?resize=630%2C148&ssl=1

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 🙂

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK