简体   繁体   中英

Why does adding <LangVersion>default</LangVersion> to a .csproj file fix a C# language version error?

I was using the "or pattern" in my C# code, but I am getting the following error:

CS8370 Feature 'or pattern' is not available in C# 7.3. Please use language version 9.0 or greater.

I am targeting .NET Framework 4.7.2 and my.csproj file does not have a <LangVersion> element. However, when I add the following element to my.csproj file, the error disappears and my code compiles correctly:

<LangVersion>default</LangVersion>

I was expecting the default value for the <LangVersion> element to just use the standard framework c# language which I expect to be c# 7.3. So why does adding this element fix the error and allow me to use the "or pattern"? Am I involuntarily using a newer c# language version and have to expect unwanted issues?

I'm using Visual Studio 17.4.1.

Here is the sample code using the pattern:

    static void Main()
    {
        var e = MyEnum.A;

        var result = e is MyEnum.A or MyEnum.B; //shows CS8370 if used without <LangVersion>default</LangVersion>

        
    }


    public enum MyEnum
    {
        A,
        B,
        C
    }

Microsoft states that the default is C# 7.3 for .net framework projects: 链接状态默认为 4.7.2。成为 C# 7.3

If you don't use <LangVersion>default</LangVersion> , Visual Studio compiler uses Frameworks C# language version default as you showed in your picture.

But if you use <LangVersion>default</LangVersion> , it uses the latest released major version of the compiler that is bundled with your Visual Studio installation.

You can see that if you scroll down more in the Microsoft page, it specifies what the "default" keyword means.

在此处输入图像描述

Additional note:

If you use default and VS2017, the "or pattern" might still not be supported due to the compiler shipping with VS2017 not being high enough version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM