C# Programming

C# is a powerful, type-safe, object-oriented language developed by Microsoft. Used for building Windows applications, web services, games, and more. Master C# with our comprehensive guide.

Why Learn C#?

  • Versatile language for desktop, web, and mobile development
  • Primary language for .NET ecosystem and Unity game development
  • Strongly typed with excellent tooling support in Visual Studio
  • High performance with access to low-level features
  • Strong enterprise adoption and job market demand

Getting Started with C#

C# is a modern, object-oriented, and type-safe programming language developed by Microsoft. It combines the power of C++ with the simplicity of Visual Basic.

Installation

Set up C# development environment:

Windows

  1. Download Visual Studio
  2. Select ".NET desktop development" workload
  3. Install and launch Visual Studio
  4. Create a new C# Console App project

macOS/Linux

Install .NET SDK:

$ sudo apt-get install dotnet-sdk // Ubuntu/Debian
$ brew install --cask dotnet-sdk // macOS

First Program

Create a file named Program.cs with this content:

// A simple C# program
using System;

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

Run it from your terminal:

$ dotnet run

C# Basics

Variables

// Variables require type declaration
string name = "Alice"; // String
int age = 30; // Integer
double height = 1.75; // Double
bool isStudent = true; // Boolean

Basic Operations

// Arithmetic operations
int x = 10 + 5; // Addition
int y = 10 * 5; // Multiplication

// String interpolation
string greeting = $"Hello, {name}!";

C# Topics

Comprehensive coverage of C# programming concepts from beginner to advanced levels

Variables & Data Types

Learn about C#'s strong typing system with primitive types, structs, enums, and reference types.

// Example of different data types
string name = "Alice"; // string
int age = 25; // int
double[] prices = {10.5, 20.3, 15.0}; // array

Control Flow

Master if-else statements, switch expressions, loops (for, while, foreach) in C#.

// If-else example
if (age >= 18) {
  Console.WriteLine("Adult");
} else {
  Console.WriteLine("Minor");
}
// For loop
for (int i = 0; i < 10; i++) {
  Console.WriteLine(i);
}

Methods

Learn to define and use methods, work with parameters, return values, and method overloading.

// Method definition
string Greet(string name) {
  return $"Hello, {name}!";
}

// Method call
string message = Greet("Alice");

Collections

Work with C#'s powerful collection types like List, Dictionary, Queue, and Stack.

// List and Dictionary examples
var fruits = new List<string> {"apple", "banana", "cherry"};
var person = new Dictionary<string, object> {
  {"name", "Alice"}, {"age", 25}
};

// Accessing elements
string firstFruit = fruits[0];
int personAge = (int)person["age"];

LINQ

Master Language Integrated Query for powerful data manipulation and transformation.

// LINQ query example
var numbers = new List<int> {1, 2, 3, 4, 5};
var evens = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);

File Handling

Learn to read from and write to files, work with streams, and manage file operations.

// Writing to a file
File.WriteAllText("file.txt", "Hello, World!");

// Reading from a file
string content = File.ReadAllText("file.txt");

Exception Handling

Understand C#'s exception handling mechanism using try-catch-finally blocks.

// Try-catch example
try {
  int result = 10 / 0;
} catch (DivideByZeroException ex) {
  Console.WriteLine("Cannot divide by zero!");
} finally {
  Console.WriteLine("Cleanup code here");
}

Object-Oriented Programming

Learn classes, objects, inheritance, polymorphism, interfaces, and other OOP concepts.

// Class definition
public class Person {
  public string Name { get; set; }
  public int Age { get; set; }

  public virtual void Greet() {
    Console.WriteLine($"Hello, I'm {Name}");
  }
}

// Creating an object
var person = new Person { Name = "Alice", Age = 25 };

Generics

Learn to create type-safe classes, methods, and interfaces that work with any data type.

// Generic class example
public class Repository<T> {
  private List<T> _items = new List<T>();

  public void Add(T item) {
    _items.Add(item);
  }
}

// Using the generic class
var repo = new Repository<string>();
repo.Add("Item 1");

Delegates & Events

Understand delegates, events, and how to implement the observer pattern in C#.

// Delegate and event example
public delegate void Notify(string message);
public class Publisher {
  public event Notify OnMessage;

  public void SendMessage(string message) {
    OnMessage?.Invoke(message);
  }
}

// Subscribing to the event
publisher.OnMessage += message => Console.WriteLine(message);

Async Programming

Learn async/await pattern, Tasks, and asynchronous operations for responsive applications.

// Async method example
public async Task<string> GetDataAsync() {
  var data = await httpClient.GetStringAsync("api/data");
  return data;
}

// Calling async method
string result = await GetDataAsync();

Entity Framework

Master ORM with Entity Framework Core for database operations and LINQ queries.

// Entity Framework example
public class AppDbContext : DbContext {
  public DbSet<Product> Products { get; set; }
}

// Querying data
var cheapProducts = await db.Products
  .Where(p => p.Price < 10)
  .ToListAsync();

ASP.NET Core

Build web applications with MVC pattern, Razor Pages, and Web API.

// Controller example
public class ProductsController : Controller {
  [HttpGet]
  public IActionResult Index() {
    return View();
  }
}

// Minimal API
app.MapGet("/products", () => {
  return Results.Ok(products);
});

Unit Testing

Learn to write unit tests for your C# code using xUnit or NUnit frameworks.

// xUnit test example
public class CalculatorTests {
  [Fact]
  public void Add_ReturnsCorrectSum() {
    var calculator = new Calculator();
    int result = calculator.Add(2, 3);
    Assert.Equal(5, result);
  }
}

Dependency Injection

Understand C#'s built-in dependency injection system for loose coupling.

// Service registration
services.AddScoped<IEmailService, EmailService>();

// Constructor injection
public class UserController {
  private readonly IEmailService _emailService;

  public UserController(IEmailService emailService) {
    _emailService = emailService;
  }
}

What Can You Build with C#?

C#'s robustness and versatility make it ideal for enterprise applications, games, and cross-platform development

Windows Applications

Build powerful Windows applications using:

  • Windows Forms (Traditional)
  • WPF (Modern UI)
  • UWP (Universal Windows)
// Simple WPF window
using System.Windows;

public class MainWindow : Window
{
  public MainWindow()
  {
    Title = "Hello World";
    Width = 400;
    Height = 300;
  }
}

Web Development

Build enterprise web applications with:

  • ASP.NET Core (Modern framework)
  • Blazor (WebAssembly/C# frontend)
  • Web APIs (RESTful services)
// Simple ASP.NET Core controller
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
  [HttpGet("/")]
  public string Index()
  {
    return "Hello World!";
  }
}

Game Development

Create professional games with:

  • Unity (Industry standard)
  • MonoGame (Cross-platform)
  • Godot (With C# support)
// Simple Unity MonoBehaviour
using UnityEngine;

public class Player : MonoBehaviour
{
  void Update()
  {
    float move = Input.GetAxis("Horizontal");
    transform.Translate(move * Time.deltaTime, 0, 0);
  }
}

Mobile Applications

Develop cross-platform mobile apps with:

  • Xamarin (Native performance)
  • .NET MAUI (Evolution of Xamarin)
  • Unity (For mobile games)
// Simple Xamarin.Forms page
using Xamarin.Forms;

public class MainPage : ContentPage
{
  public MainPage()
  {
    Content = new Label
    {
      Text = "Hello, Xamarin!",
      HorizontalOptions = LayoutOptions.Center,
      VerticalOptions = LayoutOptions.Center
    };
  }
}

Cloud Services

Build cloud-native applications with:

  • Azure Functions (Serverless)
  • Microservices with .NET
  • Docker containers
// Azure Function example
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;

public static class HelloFunction
{
  [FunctionName("Hello")]
  public static IActionResult Run(
    [HttpTrigger] HttpRequest req)
  {
    return new OkObjectResult("Hello from Azure!");
  }
}

Enterprise Applications

C# excels at building robust business apps:

  • Line-of-business applications
  • Database applications (Entity Framework)
  • Financial systems
// Entity Framework example
using Microsoft.EntityFrameworkCore;

public class CustomerContext : DbContext
{
  public DbSet<Customer> Customers { get; set; }

  protected override void OnConfiguring(
    DbContextOptionsBuilder options)
    => options.UseSqlServer("connection_string");
}

C# Learning Path

A structured approach to mastering C# programming

1 Beginner Level

  • C# Syntax and Basics

    Variables, data types, operators, and basic I/O

  • Control Flow

    Conditionals, loops, and exception handling

  • Methods and Classes

    Defining methods, basic class structure

  • Working with Files

    File I/O with System.IO namespace

2 Intermediate Level

  • Object-Oriented Programming

    Classes, inheritance, polymorphism, interfaces

  • Collections and Generics

    Lists, Dictionaries, LINQ, and IEnumerable

  • Working with APIs

    HttpClient, REST APIs, JSON serialization

  • Database Interaction

    Entity Framework Core, ADO.NET

3 Advanced Level

  • Advanced Language Features

    Delegates, events, lambda expressions

  • Asynchronous Programming

    async/await, Tasks, parallel programming

  • Dependency Injection

    IoC containers, service lifetimes

  • Performance Optimization

    Benchmarking, memory management, profiling

Ready to Master C#?

Join our C# Mastery course and get access to interactive exercises, real-world projects, and expert support to accelerate your learning.