C#
Learn how to solve CodeCrafters challenges in C#
Local development
To run the code for your challenge locally, you’ll need dotnet
installed. Our test runners use Dotnet 8.0 (as of April 2024).
The script for your challenge (like ./your_sqlite3.sh
) will automatically compile your code using dotnet
before executing it. It’ll
look something like this:
#!/bin/sh
exec dotnet run --project . --configuration Release -- "$@"
File structure
- The files for your solution are placed in the
src/
directory. src/Program.cs
contains themain
function, which is what the test runner executes.- The
.csproj
file defines project settings, target frameworks and dependencies.
Adding more files
You can add more files and directories to src/
. The test runner will include them when compiling your code.
For example, if you added a file at src/Foo.cs
, you could use it like so:
By default, all classes in src/
belong to the same namespace. This namespace is called the project namespace. E.g. If the project name is MyProject
, all classes are defined under the MyProject
namespace. This is why you can call foo()
without importing anything.
If you want to define a class under a different namespace, you’ll need to use the namespace keyword like this:
namespace AnotherNamespace {
public class Foo {
public static void foo(string[] args) {
// write code here
}
}
}
Let’s say you want to define the Foo
class in Foo.cs
under the AnotherNamespace
namespace.
Adding dependencies
You can add dependencies to your project by using dotnet
.
For example, to add the Newtonsoft.Json
package, run the following command in your terminal:
dotnet add package Newtonsoft.Json
It will also update your .csproj
file with the package reference:
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>