C# - Home
Modern C# Tutorial
Section titled “Modern C# Tutorial”Welcome to the definitive guide to C#! This tutorial is designed for both beginners and experienced developers, focusing on modern C#, the powerful .NET platform, and best practices for building robust, high-performance applications.
Introduction to C# and .NET
Section titled “Introduction to C# and .NET”C# (pronounced “C-Sharp”) is a modern, object-oriented, and type-safe programming language. Developed by Microsoft and led by Anders Hejlsberg, C# runs on the .NET platform, a free, open-source, and cross-platform framework for building all types of applications. With .NET, you can use C# to create:
- Web Applications: Scalable web APIs and web UI with ASP.NET Core and Blazor.
- Desktop Applications: Native desktop apps for Windows, macOS, and Linux using .NET MAUI and WPF.
- Cloud-Native Apps: Highly scalable microservices and serverless functions for the cloud.
- Game Development: The number one language for the popular Unity game engine.
- Mobile Apps: Cross-platform iOS and Android apps with .NET MAUI.
- AI & Machine Learning: Integrate AI into your apps with ML.NET.
Key features of this tutorial:
Section titled “Key features of this tutorial:”- Beginner-Friendly: Starts from the absolute basics and progresses to advanced topics.
- Modern C# Features: Covers modern syntax like top-level statements, string interpolation, and asynchronous programming.
Why Learn C# in 2025 and Beyond?
Section titled “Why Learn C# in 2025 and Beyond?”- High Performance: C# and .NET are known for their outstanding performance, often rivaling native languages like C++.
- Unified Platform: The modern .NET platform allows you to build for web, mobile, desktop, and cloud with a single codebase and skillset.
- Productivity: A rich standard library, a massive ecosystem of packages (NuGet), and powerful tools like Visual Studio and C# Dev Kit for VS Code make development fast and efficient.
- Open Source & Cross-Platform: Develop and deploy your C# applications on Windows, macOS, and Linux.
Getting Started with a Local C# Environment
Section titled “Getting Started with a Local C# Environment”While you can run code here, for real projects you’ll need a local setup. It’s simple:
- Install the .NET SDK: Download the latest .NET SDK from the official Microsoft website (
dotnet.microsoft.com). This includes the compiler, runtime, and thedotnetcommand-line interface (CLI). - Choose a Code Editor: Visual Studio 2022 (Windows) is the premier IDE. Visual Studio Code with the C# Dev Kit extension is a fantastic, lightweight, and cross-platform alternative.
But for now, you don’t need to install a thing. Let’s write some code!
Your First C# Program: “Hello, World!”
Section titled “Your First C# Program: “Hello, World!””Traditionally, C# programs required a fair amount of boilerplate code. Modern C# makes it much simpler with top-level statements.
// Modern C# (using top-level statements, available since C# 9)// Click "Run" to see the output!
Console.WriteLine("Hello, Modern C# World!");The Traditional Structure (For Context)
Section titled “The Traditional Structure (For Context)”It’s useful to see the structure that top-level statements hide. This is what the code above expands to:
using System;: Imports theSystemnamespace, which contains fundamental classes likeConsole.class Program: Defines a container for your program’s code.static void Main(string[] args): The official entry point of a C# application.Console.WriteLine(...): A method that prints a line of text to the console.
C# Syntax: Variables and Data Types
Section titled “C# Syntax: Variables and Data Types”Let’s declare some variables. Note the use of string interpolation ($...) for formatting strings. It’s the modern and preferred way over string concatenation (+).
string name = "Alice";int age = 30;decimal salary = 75_000.50m; // Use 'm' suffix for decimal literalsbool isEmployed = true;
// Modern way: String InterpolationConsole.WriteLine($"Name: {name}");Console.WriteLine($"Age: {age}");Console.WriteLine($"Salary: {salary:C}"); // ':C' formats as currencyConsole.WriteLine($"Is Employed: {isEmployed}");Common Data Types
Section titled “Common Data Types”| Type | Use Case | Example |
|---|---|---|
int | Whole numbers | int score = 100; |
double | Floating-point numbers (general purpose) | double pi = 3.14159; |
decimal | High-precision financial calculations | decimal price = 19.99m; |
string | Sequence of characters | string message = "Hello"; |
bool | True or false values | bool isValid = true; |
C# Control Flow
Section titled “C# Control Flow”Control flow statements direct the execution path of your program.
Robust Conditional Logic with if-else
Section titled “Robust Conditional Logic with if-else”Here’s how to handle user input safely. Instead of Convert.ToInt32(), which crashes on invalid input, the best practice is to use int.TryParse().
Console.Write("Enter your age: ");string? input = Console.ReadLine(); // string? indicates it can be null
if (int.TryParse(input, out int age)){ // This block only executes if parsing was successful if (age >= 18) { Console.WriteLine("You are eligible to vote!"); } else { Console.WriteLine("Sorry, you must be 18+ to vote."); }}else{ // Handle the case where the input was not a valid number Console.WriteLine("That's not a valid age!");}Looping with foreach
Section titled “Looping with foreach”While C# has for, while, and do-while loops, the foreach loop is often the cleanest way to iterate over a collection.
var names = new List<string> { "Alice", "Bob", "Charlie" };
Console.WriteLine("Greeting everyone:");foreach (var name in names){ Console.WriteLine($"Hello, {name}!");}C# Methods (Functions)
Section titled “C# Methods (Functions)”Methods allow you to organize code into reusable blocks. For concise methods that return a value, you can use expression-bodied syntax.
// Standard method bodyvoid Greet(string name){ Console.WriteLine($"Hello, {name}!");}
// Expression-bodied method for a simple calculationdouble Add(double a, double b) => a + b;
// --- Calling the methods ---Greet("David");
double result = Add(5.5, 4.5);Console.WriteLine($"5.5 + 4.5 = {result}");Object-Oriented Programming (OOP) in C#
Section titled “Object-Oriented Programming (OOP) in C#”C# is fundamentally object-oriented. The best practice is to use properties ({ get; set; }) to expose data, not public fields. This provides encapsulation and flexibility.
public class Car{ // Modern C# property - provides encapsulation public string Brand { get; set; } public int Year { get; private set; } // Read-only from outside the class
public Car(string brand, int year) { Brand = brand; Year = year; }
public void DisplayInfo() { Console.WriteLine($"Car Info: {Year} {Brand}"); }}
// --- Using the class ---var myCar = new Car("Tesla", 2024);myCar.DisplayInfo();
// myCar.Year = 2025; // This would cause a compile error because the setter is private.Asynchronous File Handling
Section titled “Asynchronous File Handling”In modern applications, especially those with user interfaces or network requests, it’s crucial not to block the main thread. C#‘s async and await features make asynchronous programming straightforward. You should run this code on your local machine.
using System.IO;using System.Threading.Tasks;
// Use 'await' in an async Main method or top-level statementsawait File.WriteAllTextAsync("test.txt", "Hello, Async C#!");
string content = await File.ReadAllTextAsync("test.txt");Console.WriteLine($"File Content (read asynchronously): {content}");Using async methods ensures your application remains responsive while waiting for I/O operations like reading a file to complete.
Who Should Learn C#?
Section titled “Who Should Learn C#?”C# is an excellent choice for a wide range of developers:
- Beginners & Students: A great first language with a clear syntax and strong typing that helps prevent common errors.
- Web Developers: Build fast, secure backends with ASP.NET Core and modern frontend UIs with Blazor.
- Game Developers: The primary language for Unity, the world’s most popular game engine.
- Mobile Developers: Create native iOS and Android apps from a single codebase with .NET MAUI.
- Enterprise Developers: Build robust, scalable, and maintainable systems for businesses of any size.
Start your journey with C# and .NET today to build the next generation of applications.
Prerequisites for Learning C#
Section titled “Prerequisites for Learning C#”While our tutorial is designed to be self-contained, having a basic foundation can accelerate your learning:
- No Experience Needed: We start from zero, but any prior exposure to programming concepts (variables, loops, functions) is a plus.
- Logical Thinking: A knack for problem-solving is the most important skill for any programmer.
- Curiosity: A desire to build things and understand how they work will make the learning process enjoyable and effective.
Ready to dive in? Let’s get started!