Blog
02 · C# & .NET 9 EngineeringPart 0124 min read

What Is C# and How Do You Write It? Complete Setup, Folder Structure, Syntax, OOP, and LINQ Guide

A hands-on masterclass in C# (.NET 9): from installing the SDK and understanding the project directory tree (.csproj, Program.cs, bin, obj) to data types, switch expressions, Object-Oriented Programming (Classes, Records, Interfaces), LINQ, and async/await.

Emirhan Uluksar
Emirhan Uluksar

Founder & Principal Software Architect · Digital HAT

2 views
What Is C# and How Do You Write It? Complete Setup, Folder Structure, Syntax, OOP, and LINQ Guide

Welcome to our hands-on C# engineering guide! If you want to learn C# from the ground up—knowing not just isolated syntax rules, but **which folder to create, which file to open, what every generated file in a .NET project means, and how to structure real business logic**—you are in the right place.

What We Will Build Step-by-Step in This Masterclass:
1. Step 1 — Setup & Directory Tree: Scaffolding your first .NET 9 project via CLI and inspecting .csproj, Program.cs, bin/, and obj/.
2. Step 2 — Core Syntax & Type System: Primitives, strings, GUIDs, and why financial math always uses 128-bit decimal.
3. Step 3 — Control Flow: Classic if/else and modern C# pattern-matching switch expressions.
4. Step 4 — Real Project Folder Organization & OOP: Creating Models/OrderItem.cs (record), Models/Order.cs (Encapsulated class), and Services/IOrderNotificationService.cs (interface).
5. Step 5 — LINQ & Async/Await: Querying collections declaratively and executing non-blocking I/O.
C# and .NET Development Workstation showing Classes, Async Methods and Solution Explorer

Step 1: Scaffolding Your First C# Project & Understanding the Directory Tree

After installing the .NET 9 SDK and VS Code (with C# Dev Kit), open your terminal and run these three commands:

mkdir FirstCSharpProject && cd FirstCSharpProject
dotnet new console
dotnet run

Let's inspect the exact folder and file tree generated on disk:

FirstCSharpProject/
├── FirstCSharpProject.csproj  # 1. PROJECT MANIFEST: Defines target framework (net9.0) & NuGet dependencies
├── Program.cs                 # 2. ENTRY POINT: The main C# file executed when the application starts
├── bin/                       # 3. COMPILED BINARIES: Holds compiled .dll and executable output
│   └── Debug/net9.0/
└── obj/                       # 4. COMPILER ARTIFACTS: Temporary incremental build files (Do not edit!)

Step 2: Core C# Data Types & Syntax Rules

C# Type Size Purpose Example
int 4 Bytes (32-bit) Whole numbers (-2B to +2B): Quantities, counts, IDs. int stockCount = 150;
decimal 16 Bytes (128-bit) Currency, prices, invoices, tax rates (Zero base-2 rounding errors!). decimal unitPrice = 1499.90m;
bool 1 Byte Logical true/false state. bool isPaid = true;
string Dynamic (Heap) UTF-16 text strings. string client = "Digital HAT";
Guid 16 Bytes Globally unique 128-bit identifier. Guid id = Guid.NewGuid();

Step 3: Organizing a Real Project Folder Tree with OOP (Models/ & Services/)

In real software engineering, we never dump every class into Program.cs. Let's organize our project into clean folders:

FirstCSharpProject/
├── FirstCSharpProject.csproj
├── Program.cs                        # Main entry point
├── Models/                           # Domain entities & immutable value objects
│   ├── OrderItem.cs                  # Immutable line item (record)
│   └── Order.cs                      # Encapsulated Order aggregate root (class)
└── Services/                         # Service interfaces & implementations
    ├── IOrderNotificationService.cs  # Contract (interface)
    └── EmailNotificationService.cs   # Async implementation

File 1: Models/OrderItem.cs (Immutable record)

// File: Models/OrderItem.cs
namespace FirstCSharpProject.Models;

public record OrderItem(string ProductName, int Quantity, decimal UnitPrice)
{
    public decimal LineTotal => Quantity * UnitPrice;
}

File 2: Models/Order.cs (Encapsulated class with Business Rules)

// File: Models/Order.cs
using System;
using System.Collections.Generic;
using System.Linq;

namespace FirstCSharpProject.Models;

public class Order
{
    public Guid Id { get; private set; } = Guid.NewGuid();
    public string CustomerEmail { get; private set; }
    public DateTimeOffset CreatedAt { get; private set; } = DateTimeOffset.UtcNow;
    public bool IsPaid { get; private set; }

    private readonly List<OrderItem> _items = new();
    public IReadOnlyList<OrderItem> Items => _items.AsReadOnly();

    public decimal Subtotal => _items.Sum(item => item.LineTotal);
    public decimal TaxAmount => Subtotal * 0.20m;
    public decimal GrandTotal => Subtotal + TaxAmount;

    public Order(string customerEmail)
    {
        if (string.IsNullOrWhiteSpace(customerEmail) || !customerEmail.Contains('@'))
            throw new ArgumentException("A valid customer email is required.", nameof(customerEmail));

        CustomerEmail = customerEmail.Trim().ToLowerInvariant();
    }

    public void AddItem(string productName, int quantity, decimal unitPrice)
    {
        if (IsPaid)
            throw new InvalidOperationException("Cannot add items to an already paid order.");
        if (quantity <= 0)
            throw new ArgumentOutOfRangeException(nameof(quantity), "Quantity must be at least 1.");
        if (unitPrice <= 0)
            throw new ArgumentOutOfRangeException(nameof(unitPrice), "Unit price must be positive.");

        _items.Add(new OrderItem(productName, quantity, unitPrice));
    }

    public void MarkAsPaid()
    {
        if (!_items.Any())
            throw new InvalidOperationException("Cannot pay an empty order.");

        IsPaid = true;
    }
}

File 3 & 4: Services/IOrderNotificationService.cs & EmailNotificationService.cs

// File: Services/IOrderNotificationService.cs
using System.Threading;
using System.Threading.Tasks;
using FirstCSharpProject.Models;

namespace FirstCSharpProject.Services;

public interface IOrderNotificationService
{
    Task SendOrderConfirmationAsync(Order order, CancellationToken ct = default);
}

// File: Services/EmailNotificationService.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using FirstCSharpProject.Models;

namespace FirstCSharpProject.Services;

public class EmailNotificationService : IOrderNotificationService
{
    public async Task SendOrderConfirmationAsync(Order order, CancellationToken ct = default)
    {
        await Task.Delay(100, ct); // Simulates non-blocking network SMTP I/O
        Console.WriteLine($"[EMAIL SENT] To: {order.CustomerEmail} | Order: {order.Id} | Total: {order.GrandTotal:N2}");
    }
}

File 5: Program.cs (Bringing It All Together with LINQ & Async/Await)

// File: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using FirstCSharpProject.Models;
using FirstCSharpProject.Services;

var order1 = new Order("procurement@enterprise-client.com");
order1.AddItem("SafeWork360 Enterprise License", quantity: 3, unitPrice: 15000m);
order1.AddItem("UHF RFID Gate Reader Module", quantity: 10, unitPrice: 1200m);
order1.MarkAsPaid();

var order2 = new Order("owner@bistro-chain.com");
order2.AddItem("DHRevora Cloud POS Suite", quantity: 1, unitPrice: 8500m);
order2.MarkAsPaid();

var allOrders = new List<Order> { order1, order2 };

// Query with LINQ:
var enterpriseOrders = allOrders
    .Where(o => o.IsPaid && o.GrandTotal >= 20000m)
    .OrderByDescending(o => o.GrandTotal)
    .ToList();

Console.WriteLine($"Enterprise Orders: {enterpriseOrders.Count} | Total Revenue: {allOrders.Sum(x => x.GrandTotal):N2}");

IOrderNotificationService notifier = new EmailNotificationService();
foreach (var order in allOrders)
{
    await notifier.SendOrderConfirmationAsync(order);
}

Did you find this engineering guide helpful?

Give it a like or share it with your team and network.

2 views
Share This Guide: