-1

I have a test harness in a project that was created in VS2013 (Framework 4.5). To test things out for VS2019, I added a local function (from C# 7). The project still targets 4.5, yet it compiles and runs without any errors. This isn't good - I want people to be able to go and edit in VS2013 if that's the version they got. Tell me I'm missing something simple here.

    static void Main(string[] args)
    {
        string LocalFunction()
        {
            return "yeah, im local, dude.";
        }

        Console.WriteLine(LocalFunction());
        Console.ReadKey();
    }
dbc
  • 104,963
  • 20
  • 228
  • 340
Andy
  • 67
  • 1
  • 7
  • 3
    [Language version](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version) (C# version) and Target Framework version are two different things. – jmoerdyk Apr 08 '21 at 23:23
  • 4.5 is aligned with an earlier version of the framework though, so.. do you have a solution to the issue? – Andy Apr 08 '21 at 23:25
  • c# 7.0 local functions are just syntax sugar so c# code containing them can be compiled down for earlier frameworks. See: [Does C# 7.0 work for .NET 4.5?](https://stackoverflow.com/q/42482520/3744182). To disable support for later c# language features, set `5` in Directory.Build.props as shown in [How to change C# Language Version for all of the projects in my solution in one place?](https://stackoverflow.com/q/61434436/3744182) and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#c-language-version-reference. – dbc Apr 09 '21 at 17:51
  • In fact your question may be a duplicate of [Does C# 7.0 work for .NET 4.5?](https://stackoverflow.com/q/42482520/3744182) and [How to change C# Language Version for all of the projects in my solution in one place?](https://stackoverflow.com/q/61434436/3744182). agree? – dbc Apr 09 '21 at 17:51

1 Answers1

1

Do you want to force to use the same language features? In that case, set the LangVersion property in your csproj file (or build property file) that MSBuild will recognize. For example, this will limit the language feature to C# 6 (even for .NET 5 projects):

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <LangVersion>6</LangVersion>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

Then, you will see the compile time error: enter image description here

Refer to official doc for all values you could put there.

Saar
  • 199
  • 1
  • 8