Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary Constructor Feature C#12 doesn't compile

I am trying to use the new C#12 Primary Constructor feature in a Console App but it doesn't work.

public class Foo(int x, int y)
{
    public int Z => x + y;
}
    
internal class Program
{
    static void Main(string[] args)
    {
        var x = new Foo(0,1);
    }
}

Screenshot of error

The Error is:

Class cannot have a primary constructor

My csproj:

<Project Sdk="Microsoft.NET.Sdk">  
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>    
</Project>

I am using Visual Studio Version 17.8.0 and have the sdk installed. The Language Version is C#12.

8.0.100 [C:\Program Files\dotnet\sdk]

Using a struct doesn't work either. Any idea what I am missing ?

like image 213
jeb Avatar asked Jan 30 '26 06:01

jeb


1 Answers

try adding LangVersion

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <LangVersion>12.0</LangVersion>
</PropertyGroup> 
like image 165
Gopalakrishnan R Avatar answered Feb 01 '26 22:02

Gopalakrishnan R