Tools
Log in
English

Learn to codeC#

C# project structure

Based on C# 12

Pick a console app, web API or library; get .sln, .csproj and tests as a zip.

Make a solution skeleton

Choose what to build and a code style; the folder tree, file notes and layer picture follow. Click a file to see its starter code, then download the zip and run dotnet build.

Build a
Code style
Tests

Folder tree 10 files

  • src/Acme.Hello/
  • tests/Acme.Hello.Tests/

src/Acme.Hello/Program.cs

The entry code. It reads the argument and prints the result; a missing or empty name goes to stderr with exit code 1. The modern style writes statements directly; the classic style puts them in static int Main.

using Acme.Hello; if (args.Length == 0){    Console.Error.WriteLine("usage: dotnet run -- <name>");    return 1;} var greeter = new Greeter();try{    Console.WriteLine(greeter.Greet(args[0]));    return 0;}catch (ArgumentException e){    Console.Error.WriteLine(e.Message);    return 1;} 

Layers

Versions written in the files .NET 8 SDK · C# 12 · xUnit 2.5.3 · Microsoft.NET.Test.Sdk 17.8.0. NuGet packages are not in the zip. With the test project included, the first dotnet build downloads xUnit.

Where things go in a .NET solution

PathWhat goes there
*.slnThe solution file. It groups several projects; dotnet build in the top folder builds every project listed here.
*.csprojThe project file (src/Name/Name.csproj): target framework (net8.0), app or library, packages and references to other projects. Every .cs file in the folder is included without listing it.
Program.csThe entry code. The modern style writes code directly at the top of the file (top-level statements); the classic style uses static void Main.
tests/The test project (tests/Name.Tests/). It references the main project, pulls in a test package such as xUnit, and runs with dotnet test.
appsettings.jsonSettings for a web project. The development-only launch profile lives in Properties/launchSettings.json. Secrets go into user-secrets or environment variables, not here.
bin/ · obj/Build output and intermediate files. They come back after a rebuild, so keep them out of git.

By convention the folder path matches the namespace: files in src/Acme.Hello/Services/ start with namespace Acme.Hello.Services;.

Splitting into layers

Separate the part that takes requests, the part that decides rules and the part that stores data. In a web API, the endpoint in Program.cs (MapGet) calls GreetingService, which calls IMessageRepository, never the other way round.

ASP.NET Core ships with a dependency injection container: register a type with builder.Services.AddSingleton<...>() and endpoints receive the right object as a parameter.

  • Endpoints take values from the request, pass them to a service and shape the response.
  • Services decide the rules and know nothing about HTTP, so they are easy to test.
  • Repositories sit behind an interface: a memory version now, a database version swapped in later.

Naming

Name namespaces and projects Company.Product, with a capital letter on each word (Acme.Hello). The test project adds .Tests.

  • Classes, methods and properties use PascalCase (MonthlyPay), locals and parameters camelCase (teamSize), and interfaces start with I (IBackup).
  • Avoid System, Console or Microsoft in your namespace. Inside Acme.Console, Console.WriteLine resolves to the namespace and fails.
  • One public type per file, with the file named after the type, keeps things easy to find (a habit, not a rule).

Four common design patterns and dependency injection

When to use each matters more than the name. All of this code was built and run on .NET 8.

Singleton · when there must be exactly one

For objects like settings that must exist once in the whole program. The constructor is private; you get the object only through Instance. Lazy<T> creates it once, on first use, safely across threads.

In ASP.NET Core, registering it with AddSingleton is easier to test than writing it by hand.

var a = AppSettings.Instance;var b = AppSettings.Instance;Console.WriteLine(ReferenceEquals(a, b));Console.WriteLine(a.Mode); sealed class AppSettings{    private static readonly Lazy<AppSettings> lazy = new(() => new AppSettings());     public static AppSettings Instance => lazy.Value;    public string Mode { get; } = "production";     private AppSettings()    {    }}

Output

Trueproduction

Factory · deciding what to create in one place

A method that looks at the file extension and returns the right reader. A switch expression keeps it short, and unknown extensions raise an exception. Callers only know they get an IReader.

IReader reader = ReaderFactory.For("members.csv");Console.WriteLine(string.Join(" | ", reader.Read("kim;25;seoul"))); interface IReader{    string[] Read(string line);} class CsvReader : IReader{    public string[] Read(string line) => line.Split(';');} class TsvReader : IReader{    public string[] Read(string line) => line.Split('\t');} static class ReaderFactory{    public static IReader For(string fileName) => Path.GetExtension(fileName) switch    {        ".csv" => new CsvReader(),        ".tsv" => new TsvReader(),        _ => throw new NotSupportedException(fileName),    };}

Output

kim | 25 | seoul

Strategy · swappable ways to calculate

Pull a calculation with several variants, such as discounts, into an interface and pick one when creating the object. Here C# 12 primary constructors (class Checkout(IDiscount discount)) keep the wiring short. Simple rules can also be a Func<decimal, decimal> lambda.

var regular = new Checkout(new NoDiscount());var member = new Checkout(new PercentOff(15));var coupon = new Checkout(new FuncDiscount(price => price - 5_000m));Console.WriteLine(regular.Pay(20_000m));Console.WriteLine(member.Pay(20_000m));Console.WriteLine(coupon.Pay(20_000m)); interface IDiscount{    decimal Apply(decimal price);} class NoDiscount : IDiscount{    public decimal Apply(decimal price) => price;} class PercentOff(int percent) : IDiscount{    public decimal Apply(decimal price) => price * (100 - percent) / 100;} class FuncDiscount(Func<decimal, decimal> rule) : IDiscount{    public decimal Apply(decimal price) => rule(price);} class Checkout(IDiscount discount){    public decimal Pay(decimal price) => discount.Apply(price);}

Output

200001700015000

Observer · telling others when something happens

C# builds this pattern into the language as event. Listeners sign up with +=, and the sender notifies all of them with one Restocked?.Invoke(...) line. With no listeners, ?. simply skips the call.

var shop = new Stock();shop.Restocked += item => Console.WriteLine($"Mail: {item} is back");shop.Restocked += item => Console.WriteLine($"Log: restocked {item}");shop.Restock("keyboard"); class Stock{    public event Action<string>? Restocked;     public void Restock(string item)    {        Restocked?.Invoke(item);    }}

Output

Mail: keyboard is backLog: restocked keyboard

Dependency injection · receiving what you need through the constructor

GreetingService does not create its name store with new; it receives one in the constructor. The real program passes the memory store, and a test passes a fake that always returns the same name.

This is what builder.Services in ASP.NET Core does: it finds the registered implementation and passes it to the constructor (see the web API starter files).

var real = new GreetingService(new MemoryNames());Console.WriteLine(real.Greet(1));Console.WriteLine(real.Greet(7));var test = new GreetingService(new FakeNames("Tester"));Console.WriteLine(test.Greet(1)); interface INameStore{    string? Find(int id);} class MemoryNames : INameStore{    private readonly Dictionary<int, string> names = new() { [1] = "Mina" };     public string? Find(int id) => names.GetValueOrDefault(id);} class FakeNames(string name) : INameStore{    public string? Find(int id) => name;} class GreetingService(INameStore store){    public string Greet(int id) => $"Hello, {store.Find(id) ?? "guest"}";}

Output

Hello, MinaHello, guestHello, Tester

Check yourself

Question 1

Which folders stay out of git?

Show the answer

Answer: 3. bin/ · obj/ bin/ and obj/ hold build output that is recreated on every build. List them in .gitignore; whoever clones the repository runs dotnet build to get them back.

Question 2

Which way do the references go between the main project and the test project?

Show the answer

Answer: 1. The test project references the main project The test project lists the main project with a ProjectReference in its .csproj. The main project must not know about the tests, so xUnit never ships with your app.

Questions people ask

What is the difference between .sln and .csproj?

A .csproj configures one project (one app or dll); a .sln lists several projects as a group. The solution lets you build the main project and its tests together.

How do I build the zip I downloaded?

Run dotnet build in the top folder and dotnet test for the tests. Run the console app with dotnet run --project src/Name -- Mina. README.md in the zip lists every command.

Should I pick the modern or the classic style?

For new code, the modern style (top-level statements, file-scoped namespaces) is shorter and matches dotnet new. Pick classic to match older code or books. Both build to the same result.