nameof get's a bit better in C# 12

5/28/2023

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.

Less boilerplate code with the new primary constructor in C# 12

The new language feature "primary constructor" which will be released with C# 12 / .NET 8 this year (November 2023) allows you to remove some ceremonial code. Let's see how.

C# 12: Collection literals

A new feature is hitting C# 12 and it is called Collection literals. In this blog post, I will show you what it is and how it works.

C# 12: Primary Constructors

Another new C# 12 feature might drop soon and makes its debut with the next iteration: Primary Constructors.

The blog post will talk about what a Primary constructor is, why we already have it, and what the proposal tries to change. Exciting times are ahead of us!

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