Pages

Thursday, April 27, 2023

C# 12.0 Preview: Primary Constructors for Classes and Structs

In this post let's have a look at "Primary Constructors for Classes and Structs", a preview feature in C# 12.0. You can try this out with the latest Preview versions of Visual Studio 2022 and .NET 8. And make sure to LangVersion as preview.

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

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <LangVersion>preview</LangVersion> ...
  </PropertyGroup>

</Project>

Consider the following example using C# latest stable (C# 11.0) version.

public class BlogPost
{
    public BlogPost(string title, IEnumerable<stringtags)
    {
        Title = title;
        Tags = tags;
    }

    public BlogPost(string title) : this(title, Enumerable.Empty<string>())
    {
    }

    public string Title { getinit; }

    public IEnumerable<string> Tags { getset; }
}

I can write the same code as follows using C# 12.0 Preview.

public class BlogPost(string title, IEnumerable<stringtags)
{
    public BlogPost(string title) : this(title, Enumerable.Empty<string>())     {
    }

    public string Title => title;

    public IEnumerable<string> Tags { getset; } = tags;
}

The important thing to note here is, we have added parameters to the class declaration itself and we can use these values in the class body. It's kind of the same as the primary constructors that were introduced for records in C# 9, but in records, properties are automatically created for primary constructor parameters. But due to complexity and use case differences between records and classes/structs, Primary Constructors for Classes and Structs won't be creating properties automatically.

A class with a primary constructor can have additional constructors just like we have above. But all those constructors much ensure the primary constructor is being called using this(...). It can be a direct call to the primary constructor or calling another constructor that in turn calls the primary constructor, something like below.

public class BlogPost(string title, IEnumerable<stringtags)
{
    public BlogPost(string title) : this(title, Enumerable.Empty<string>())     {
    }

    public BlogPost() : this("Default Title")
    {
    }

    ...
}

Read more,
   What’s new in C# 12: Primary Constructors

Hope this helps!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment