Search code examples
c#compiler-errorsrecord.net-5c#-9.0

Why do I get compilation error when trying to use record type in C#?


EDIT: Thank you everyone! I have never upgraded to a newer version of .NET and language version before. Thus didn't know about .csproj configuration. Even though I did a research before posting a question I was not able to find a solution myself. So, I just leave these two links for further reference, perhaps this might help someone as well.

https://learn.microsoft.com/en-us/dotnet/standard/frameworks

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version

I have upgraded to .NET 5.0.301

And finally got around to try record type in C# 9.0

I wrote a simple code but got an error during compilation.

I use Visual Studio Code as an editor.

VS Code version 1.57.0

C# extension version 1.23.12

Here is my settings.json:

"editor.semanticHighlighting.enabled": true,
"csharp.semanticHighlighting.enabled": true,
"omnisharp.path": "latest"

Set up:

dotnet new sln -n "Test"
dotnet new console -n "TestProject"
dotnet sln Test.sln add  .\TestProject\TestProject.csproj

My code:

using System;

namespace TestProject
{

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person() { Name = "Tom" };
            person.Name = "Bob";
            Console.WriteLine(person.Name);
        }
    }

    public record Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

}

Problems:

CS0246 The type or namespace name 'Person' could not be found (are you missing a using directive or an assembly reference?)
CS0246 The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
CS0548 '<invalid-global-code>.Person': property or indexer must have at least one accessor
CS1513 } expected
CS0116 A namespace cannot directly contain members such as fields or methods
CS1022 Type or namespace definition, or end-of-file expected

Any help much appreciated


Solution

  • Check your target framework and language version in your .csproj file. You should find something like:

    <TargetFramework>net5.0</TargetFramework>
    <LangVersion>9.0</LangVersion>
    

    If you don't find these properties, add them inside the <PropertyGroup>...</PropertyGroup> tags. If they are set to older versions, change them.

    If this does not solve your problem, you may have installed your .NET SDK incorrectly, or you may have installed it in a directory other than the default one and the VS Code C# extension is not able to find it.