C# Introduction

C# (C-sharp) is a modern, type-safe, object-oriented language developed by Microsoft. It's the primary language for .NET development, used for web apps (ASP.NET), desktop (WPF/Maui), games (Unity), and cloud services.

Why C#?

  • Modern syntax — Clean, expressive, continually evolving
  • Powerful type system — Generics, nullable reference types, pattern matching
  • LINQ — Query any collection with SQL-like syntax
  • Async/await — First-class async support
  • Unity — #1 language for game development
  • Cross-platform — .NET runs on Windows, Linux, macOS, mobile, web
  • Enterprise — Used by Fortune 500 companies worldwide

Hello World

CSHARP
// Top-level statements (C# 9+)
Console.WriteLine("Hello, World!");

// Or traditional
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Variables and Types

CSHARP
// Basic types
string name = "Alice";
int age = 28;
double pi = 3.14159;
bool active = true;
decimal price = 29.99m;

// Type inference
var x = 42;           // int
var greeting = "Hi";  // string

// Nullable types (nullable reference types enabled by default in .NET 6+)
string? maybeName = null;
int? maybeAge = null;

// Null handling
Console.WriteLine(maybeName ?? "default");      // Default value
Console.WriteLine(maybeName?.Length ?? 0);      // Safe access
Console.WriteLine(maybeName!);                  // Force unwrap (dangerous)

// String interpolation
var message = $"Hello, {name}! You are {age} years old.";

// Raw string literals (C# 11)
var json = """
    {
        "name": "Alice",
        "age": 28
    }
    """;

// Collections
var list = new List<int> { 1, 2, 3, 4, 5 };
var dict = new Dictionary<string, int> {
    ["Alice"] = 95,
    ["Bob"] = 87
};
var array = new[] { 1, 2, 3 };

Methods and Properties

CSHARP
// Method
public static int Add(int a, int b) => a + b;

// Expression-bodied members
public static int Square(int x) => x * x;

// Properties
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; init; }  // Init-only (C# 9)
    
    // Computed property
    public bool IsAdult => Age >= 18;
    
    // Constructor
    public Person(string name, int age, string email)
    {
        Name = name;
        Age = age;
        Email = email;
    }
    
    // Primary constructor (C# 12)
    // public class Person(string name, int age, string email);
    
    public override string ToString() => $"{Name} ({Age})";
}

Collections and LINQ

CSHARP
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// LINQ — query collections with SQL-like syntax
var evens = numbers.Where(n => n % 2 == 0).ToList();     // [2,4,6,8,10]
var doubled = numbers.Select(n => n * 2).ToList();       // [2,4,6,...,20]
var total = numbers.Sum();                                 // 55
var avg = numbers.Average();                               // 5.5

// Chaining
var result = numbers
    .Where(n => n > 3)
    .Select(n => n * n)
    .OrderByDescending(n => n)
    .Take(3)
    .ToList();  // [100, 81, 64]

// Grouping
var words = new[] { "apple", "banana", "cherry", "avocado" };
var grouped = words.GroupBy(w => w[0]);  // Group by first letter

// Query syntax (SQL-like)
var query = from n in numbers
            where n > 3
            select n * n;

Async/Await

CSHARP
// Async method
public async Task<string> FetchDataAsync(string url)
{
    using var client = new HttpClient();
    var response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();
}

// Usage
var data = await FetchDataAsync("https://api.example.com/data");

// Parallel execution
var tasks = urls.Select(url => FetchDataAsync(url));
var results = await Task.WhenAll(tasks);

// Cancellation
var cts = new CancellationTokenSource();
var task = LongRunningOperationAsync(cts.Token);
cts.Cancel();  // Cancel after timeout

Pattern Matching

CSHARP
// Switch expression
string GetGrade(int score) => score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

// Type pattern
object obj = "Hello";
if (obj is string s && s.Length > 3)
{
    Console.WriteLine(s.ToUpper());
}

// Property pattern
if (person is { Age: >= 18, Name.Length: > 0 })
{
    Console.WriteLine($"Adult: {person.Name}");
}

💡 Tip: Use LINQ for all collection operations instead of manual loops. It's more expressive and the compiler optimizes it just as well.

Next: C# Control Flow