C# logo

C# Beginner

Multi-paradigm language — enterprise-grade OOP, cross-platform performance via .NET, native garbage collection, and powerful type-safe queries.

1 Entry Point & Variables

Modern C# implements **Top-Level Statements**, removing boilerplate code like namespaces and class declarations for entry files. Variables can use explicit types or infer them via the var keyword while maintaining strict type safety.

cs · Program.cs
// Single-line comment
/* Multi-line comment block */

using System;

string project = "testProject";
var operationalState = "Active"; // Implicitly typed as string

// String interpolation using the $ prefix
Console.WriteLine($"System core: {project} is currently {operationalState}.");

2 Data Types & Generics

C# distinguishes between Value Types (stored on the stack) and Reference Types (stored on the heap). Collections like List<T> enforce type safety through generics.

int / long 32-bit and 64-bit signed integers int userId = 404;
decimal 128-bit high precision financial type decimal balance = 1532.50m;
bool Standard boolean true/false state bool isAuth = true;
string Immutable sequence of UTF-16 characters string route = "/api/v1";
List<T> Strongly-typed dynamic array list var tags = new List<string>();
Nullable<T> / T? Wraps value types to allow null values int? index = null;

3 Conditionals & Logic Operations

Control application flow using standard if, else if, and else evaluation statements alongside explicit relational tracking operators.

cs · ControlFlow.cs
int statusCode = 201;

if (statusCode == 200 || statusCode == 201) {
    Console.WriteLine("Request processed successfully.");
} else if (statusCode >= 400 && statusCode < 500) {
    Console.WriteLine("Client execution error handled.");
} else {
    Console.WriteLine("Server or network fallback triggered.");
}

4 Loops & Advanced Switch Patterns

Iterate over lists securely using foreach blocks. Modern C# also introduces powerful **Switch Expressions** that parse value configurations cleanly.

cs · LoopsAndSwitch.cs
var platforms = new[] { "Web", "Android", "iOS" };

foreach (var platform in platforms) {
    // C# 8+ Switch expression pattern matching assignment
    string accessLayer = platform switch {
        "Web"     => "Browser runtime execution",
        "Android" => "Native APK bytecode environment",
        _         => "Generic architectural layer" // Discard fallback
    };
    Console.WriteLine($"{platform}: {accessLayer}");
}

5 Methods & Auto-Properties

Methods declare parameters with strict visibility and return signatures. Use shorthand expressions (=>) for simple operations, and leverage **Auto-Implemented Properties** to safely encapsulate state fields.

cs · Encapsulation.cs
public class AccountMetric {
    // Auto-property with restricted write access modifier
    public string Currency { get; private set; } = "EUR";

    // Expression-bodied method mapping signature
    public bool IsValidTransaction(decimal value) => value > 0.00m;
}

6 OOP Architecture & Records

C# implements a classic Object-Oriented paradigm featuring single class inheritance and explicit interface contracts. It also supports **Records**, which provide lightweight, immutable data structures out of the box.

cs · Inheritance.cs
public interface IRepository {
    void SaveState();
}

// Class inheritance and explicit interface contract realization
public class DbContext : IRepository {
    public void SaveState() => Console.WriteLine("Database persistence executed.");
}

// Immutable positional record model definition (C# 9+)
public record UserProfile(string Username, string Email);
Classes use reference equality, whereas **Records implement value-based equality checking automatically**. Comparing two identical record instances with == evaluates to true.

7 Exceptions & Safe Resource Management

Handle runtime faults gracefully using try-catch-finally blocks. For external resources like network links or file streams, always use the using declaration statement to guarantee memory cleanup through `IDisposable` execution blocks.

cs · ExecutionSafety.cs
try {
    // Modern scope-bound using statement layout context
    using var stream = new System.IO.StreamWriter("log.txt");
    stream.WriteLine("Appending structural metadata block.");
} 
catch (System.IO.IOException ex) {
    Console.WriteLine($"Disk storage mutation fault recorded: {ex.Message}");
} 
catch (Exception ex) {
    Console.WriteLine($"Uncaught base execution error: {ex.Message}");
}

8 Data Querying via LINQ Expressions

**Language Integrated Query (LINQ)** provides a powerful, type-safe syntax to filter, transform, and aggregate data collections cleanly—whether operating on arrays or remote database entities.

cs · LinqQueries.cs
var transactions = new List<decimal> { 120.50m, -45.00m, 300.00m, -12.30m };

// Clean method syntax query pipeline filtering values
var highProfits = transactions
    .Where(tx => tx > 100.00m)
    .OrderByDescending(tx => tx);

foreach (var profit in highProfits) {
    Console.WriteLine($"Filtered profit target node value: {profit}");
}
With C# fundamentals solidified, you are ready to build cross-platform APIs using **ASP.NET Core** frameworks or integrate performant entity mappers like **Entity Framework Core**.