nameof get's a bit better in C# 12

28/05/2023
C# 12.NETC#

The nameof operator is a great way to get the name of a variable, type, or member. With C# 12 it's getting even better. Let's see how.

What is nameof?

nameof is a C# operator that returns the name of a variable, type, or member as a string. It's a great way to get the name of something without having to hardcode it as a string. Here a quick example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Console.WriteLine(nameof(person.FirstName)); // FirstName
Console.WriteLine(nameof(Person)); // Person

What's new in C# 12?

With C# 12, nameof is getting an upgrade: You can access instance data from a static context. Let's see what that means.

public class NameofClass
{
    public string SomeProperty { get; set; }

    // Now legal with C# 12
    public const string NameOfSomePropertyLength = nameof(SomeProperty.Length);
}

In C# 11 and earlier, this would result in a compiler error and even if you use C# 12 it still results in one:

[CS8652] The feature 'instance member in 'nameof'' is currently in Preview and unsupported. To use Preview features, use the 'preview' language version.

That means that the feature itself is considered preview (and therefore might not make the cut as stable feature into C# 12). To overcome that fact, you have to extend the csproj file:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <LangVersion>preview</LangVersion>
        <!-- This enables preview features -->
        <EnablePreviewFeatures>true</EnablePreviewFeatures>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

</Project>

Now it compiles and would show "Length" on the console if you would print NameOfSomePropertyLength to the console.

Conclusion

nameof is a handy operator that improved with the upcoming C# 12. Nothing big, but still a nice improvement. If you want to know more, here is the official GitHub Proposal.

3
An error has occurred. This application may no longer respond until reloaded. Reload x