16 November

C# 11 – Extended name of the scope

min. read

Reading Time: < 1 minute
C# 11
C# 11

Let’s list all the features that C# 11 brings to the table. Let’s discuss them all one by one, with their use cases, and see how they can come in handy. At the bottom of each article, you can find a link to all 14 new C# features!

Extended name of the scope

In times before C# 11, we could only provide nameof the parameter after the declaration took place.

So something like this:

// C# 10
public class MyClass
{
   [Description('myParam')] // Cannot use nameof :(
   public void MyMethod(string myParam)
   {
       var nameOfClass = nameof(MyClass);
       var nameOfMethod = nameof(MyMethod);
       var nameOfParam = nameof(myParam);
   }
}

anything other than that would result in a build-time exception.

In new C# 11, you can also put those nameof before declaration on certain elements.

// C# 11
public class MyClass
{
   [Description(nameof(myParam))] // It works!
   public void MyMethod(string myParam)
   {
       [Description(nameof(TGeneric))]
       void LocalFunction<TGeneric>(TGeneric param) { }

       var lambda = ([Description(nameof parameter)] string parameter) => 
          Console.WriteLine(parameter);
   }
}

As you can see this also works for local functions and lambda expressions. For parameters and generic attributes. Brilliant!

Further reading at dotnet GitHub page.

Current article:
Extended name of the scope


Author

Tomasz Juszczak

CTO /

Technical Lead

Tomasz Juszczak

About prog

Founded in 2016 in Warsaw, Poland. Prographers mission is to help the world put the sofware to work in new ways, through the delivery of custom tailored 3D and web applications to match the needs of the customers.


Let's talk

SEND THE EMAIL