Project Properties

I’m working on standardizing my code using the latest and greatest .NET features. For me, that currently means adding the following to the first <PropertyGroup> section in my csproj file:

<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
  • LangVersion: Allows me to use the latest features in C#, like switch expressions, tuple patterns, and using declarations.
  • Nullable: Incorporating nullable reference types, which is new and weird, but it’s a fantastic way to greatly reduce unnecessary null-checking and NullReferenceException errors.
  • TreatWarningsAsErrors and WarningsAsErrors: Honestly, I started reading what the difference is between these, and I gave up, so I just said screw it and put both in there. This marks compiler warnings as errors, forcing me to follow my own standards.
    • My configuration in Visual Studio (in 2019: Tools/Options/Text Editor/C#/Code Style) is set pretty strict, where a lot of the typically “Refactoring Only” options are set to “Error”. Your style and preferences are of course up to you and your team.

Also, I pretty much always use an appsettings.json file, and I want it in the output directory, so I add:

<ItemGroup>
    <None Update="appsettings.json">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
</ItemGroup>

In a console app, I’ll need to add a reference to the appropriate package:

dotnet add package Microsoft.Extensions.Configuration.Json

And the code to load it:

using Microsoft.Extensions.Configuration;

private static IConfiguration _config;

static void Main() {
    _config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    // ...
}