Zero to Project: C# on Linux

Continuing with how to setup languages, this time with C#.NET 5.0.

Installing

dotnet --version should print correctly, and that’s it. The C# extension will call dotnet from PATH.

Creating a solution

Create a new solution:

dotnet new sln -o MySolution

In the folder that was created, create a new CLI project (run in a blank folder):

dotnet new console -o MyProject #or (dotnet new classlib for a library project)
dotnet build
dotnet run

To debug through VS code, create a launch.json automatically and run. This builds the project using dotnet build (with whatever is in your .csproj) and runs with debug. To disable the lengthy module load logs, add this to the launch configuration:

1
2
3
"logging": {
"moduleLoad": false
}

You can change the main class by adding this to the property group in the .csproj under <PropertyGroup>:

1
<StartupObject>csharp.Day10</StartupObject>

Dependencies

Adding dependencies is easy too, for example to add the YamlDotNet library through NuGet:

dotnet add package YamlDotNet

This simple adds a dependency to your .csproj:

1
2
3
<ItemGroup>
<PackageReference Include="YamlDotNet" Version="9.1.0" />
</ItemGroup>

Unit tests

To add unit tests, create an xunit project under the same solution with tests in it, and add the original project as a dependency:

dotnet new xunit -o MyProject.Tests
dotnet add ./MyProject.Tests/MyProject.Tests.csproj reference ./MyProject/MyProject.csproj
dotnet sln add ./MyProject.Tests/MyProject.Tests.csproj

Unfortunately, the C# extension must be in the project folder to work well, so making a single .vscode folder for the entire solution is not a good idea.

Now to run it:

  • You can click on Debug test above a unit test to launch it (or Debug All Tests to run a unit test class).
  • The .NET Core Test Explorer can assist in watching many unit tests, but it cannot debug.
  • You can create a main method that calls all the unit tests and launch it with a launch.json but this is obviously not ideal.

More on how to organize a .NET Core project and C# Unit tests. I ended up just using the “debug test” button.

My resulting project is here.

I’m new to C#, what’s next?