Monday, July 17, 2023

C# 12.0 Preview: Access Instance Members within nameof

In this post, let's go through a new feature that's coming with C# 12.0. With this feature, you can access instance members within nameof.

To try this feature out, make sure you have the latest version of .NET SDK (>= 8.0.0-preview.6) installed and the <LangVersion> is set to preview.
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    ...
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

</Project>
Let's consider the following example.
using System.ComponentModel;

Console.WriteLine(nameof(NameOfHelper.StaticInteger.MinValue));

internal class NameOfHelper
{
    public string MyString { get; } = "SomeValue";

    public static int StaticInteger;
    public string NameOfLength { get; } = nameof(MyString.Length);

    [Description($"Returns {nameof(MyString.Length)} of given String")]
    public int StringLength(string s) => s.Length;
}
With the above code, if we use a C# <LangVersion> prior to 12.0, we will get compile errors when using these nameof expressions. Because we are using nameof to access instance members.

But with C# 12.0, it would build just build fine.
nameof()
Check out more C# 12 features:

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment