9

Introducing C#11: Extended nameof parameter scope

 1 year ago
source link: https://anthonygiretti.com/2022/12/04/introducing-c11-extended-nameof-parameter-scope/
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#11: Extended nameof parameter scope

2022-12-04 by anthonygiretti

Introduction

C# 11 brings a novelty in the use of a method or parameter attribute. Usually it is impossible for an attribute to know the parameter of a method or of the parameter itself on which the attribute is applied, because they are not in the same scope. You just get a compilation error. C# 11 fixes this when you use nameof and only nameof on a parameter. I will show you an example in this post.

Example

The code below defines an attribute that logs parameters passed to it in the Visual Studio console. In itself there is nothing extraordinary it is a simple attribute, however I will show you later that we can pass parameters to it which are the result of a nameof (parameter) on the method to which it has been applied:

Now let’s use a minimal API to log the name of the parameters with our attribute:

The result on execution is this:

nameofonattributecsharp11.png

Before C# 11 you would have got the following error at the compilation:

image.png

Conclusion

As I write these lines I don’t really have a relevant use case to show you, I showed you a really basic example that won’t necessarily be useful in your everyday life. So I’m going to ask you a little favor: Leave me a comment if you have a relevant use case in mind, I’ll appreciate it 🙂

Like this:


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK