SHARE:

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 🙂

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: