16 November

C# 11 – Extended name of the scope

Programming

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


Let's talk

SEND THE EMAIL

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.