Introducing C#11: Extended nameof parameter scope
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.
Introducing C#11: Extended nameof parameter scope
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:
Before C# 11 you would have got the following error at the compilation:
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
-
9
C#11 Parameter Null Checking Such is life on Twitter, I’ve been watching from afar .NET developers argue about a particular upcoming C# 11 feature, Parameter Null Checks. It’s actually just a bit of syntactic sugar to make it easier to throw...
-
4
Introducing C#11: Auto Default structs 2022-09-28 by anthonygiretti Introduction
-
22
Introducing C#11: Raw string literals 2022-11-29 by anthonygiretti Introduction
-
3
Introducing C#11: List Pattern 2022-11-29 by anthonygiretti Introduction With
-
6
Introducing C#11: Required properties 2022-12-02 by anthonygiretti Introduction
-
6
Introducing C#11: Pattern match Span and ReadonlySpan on a constant string 2022-12-04 by anthonygiretti ...
-
11
Introducing C#11: Newlines in string interpolation expressions 2022-12-04 by anthonygiretti Introduction
-
7
Introducing C#11: File local types 2022-12-04 by anthonygiretti Introduction Have you ever developed/consumed...
-
7
Introducing C#11: UTF-8 String Literals 2022-12-04 by anthonygiretti Introduction .NET encodes strings with U...
-
3
.NET Tools How-To's Required Key...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK