Skip to content

C# - Home

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.

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.
  • 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.
  • 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 the dotnet command-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!");

It’s useful to see the structure that top-level statements hide. This is what the code above expands to:

  1. using System;: Imports the System namespace, which contains fundamental classes like Console.
  2. class Program: Defines a container for your program’s code.
  3. static void Main(string[] args): The official entry point of a C# application.
  4. Console.WriteLine(...): A method that prints a line of text to the console.

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 literals
bool isEmployed = true;
// Modern way: String Interpolation
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Salary: {salary:C}"); // ':C' formats as currency
Console.WriteLine($"Is Employed: {isEmployed}");
TypeUse CaseExample
intWhole numbersint score = 100;
doubleFloating-point numbers (general purpose)double pi = 3.14159;
decimalHigh-precision financial calculationsdecimal price = 19.99m;
stringSequence of charactersstring message = "Hello";
boolTrue or false valuesbool isValid = true;

Control flow statements direct the execution path of your program.

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!");
}

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}!");
}

Methods allow you to organize code into reusable blocks. For concise methods that return a value, you can use expression-bodied syntax.

// Standard method body
void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// Expression-bodied method for a simple calculation
double 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}");

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.

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 statements
await 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.

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.

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!