Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Beginners Guide: Overview, Features, and Learning Path

Beginners Guide: Overview, Features, and Learning Path

This page covers C# syntax, features, and recommended learning order. It covers static typing and GC-based memory management, LINQ for data operations, async/await for asynchronous code, how execution works (IL/CLR), and the development toolchain.

For the history of C# — including the Microsoft–Sun conflict that triggered its creation, Anders Hejlsberg's design philosophy, the version timeline, and C#'s relationships with other languages — see History and Lineage of C#.

What Is C#? (In a Nutshell)

C# is a statically typed, general-purpose language that combines Java's memory safety, C-family syntax, and Delphi's developer productivity, officially released in 2002. It runs on Microsoft's .NET platform and, since .NET 5 (2020), works on Windows, Linux, and macOS. Unity games are scripted exclusively in C#, and ASP.NET Core is the primary web backend framework for .NET.

For the founding story, Hejlsberg's design philosophy, version evolution, and influence on other languages, see History and Lineage of C#.

File Extensions

C# source code is saved with the following file extensions.

  • .cs — C# source file
  • .csproj — Project configuration file (XML)

Five Points to Know Before You Start

  • C# is statically typed — type mismatches are caught at compile time. Variables are declared with an explicit type, or with var to let the compiler infer it.
  • Memory is managed automatically by the garbage collector (GC). No manual malloc/free is needed. In real-time systems, be aware of GC pauses.
  • LINQ is one of C#'s signature features. Arrays, lists, databases, and XML can all be filtered, sorted, and aggregated using the same unified syntax.
  • async/await lets you write asynchronous code in a synchronous style. C# pioneered this syntax, which was later adopted by JavaScript, Python, Kotlin, and Rust.
  • Execution is a two-stage process: IL (intermediate code) → CLR (JIT or AOT). The same IL file runs on Windows, Linux, and macOS — the same idea as Java bytecode + JVM.

For C#'s founding story, design philosophy, and family tree, see History and Lineage of C#.

C# Features — Strengths and Trade-offs

C# has characteristics that set it apart from other languages, and each characteristic can be both a strength and a weakness. It is not a matter of which is better — the right fit depends on the project's scale, purpose, and team structure.

Statically typed language

C# is a statically typed language: variables, parameters, and return values must have explicit types. Type mismatches are detected at compile time (before execution).

string name = "item_a1";
int score = 80;

// Attempting to assign the wrong type causes a compile error
// name = 100; // error: cannot implicitly convert type 'int' to 'string'

The extra type declarations increase the amount of code, but they enable precise IDE (Integrated Development Environment — a tool combining code editing, execution, and debugging) autocompletion and catch type-mismatch bugs before the program even runs.

Garbage collection

In C and C++, programmers must manually allocate and free memory. In C#, a garbage collector (GC) automatically reclaims memory that is no longer needed.

This removes the burden of memory management, but the GC can cause brief pauses when it runs (known as "GC pauses"). In systems where real-time responsiveness is critical, these pauses can become a problem.

LINQ — unified syntax for data manipulation

C# has a feature called LINQ (Language Integrated Query, pronounced "link"). It lets you filter, sort, and aggregate arrays, lists, databases, XML, and other data sources using a single unified syntax.

var numbers = new List<int> { 5, 12, 3, 8, 20 };

// Get numbers greater than 10, in ascending order
var result = numbers.Where(n => n > 10).OrderBy(n => n);

Writing SQL-like expressions directly in code makes collection operations concise.

C# feature summary

FeatureStrengthWeakness / Note
Static typingType mismatches caught before executionMore code to write
Garbage collectionNo need to think about memory managementGC pauses can occur
LINQConcise collection operationsTakes time to read and write until you get used to it
.NET platformRich libraries and long-term supportEcosystem is Microsoft-led
Unity supportUsed as Unity's scripting languageUnity's C# version may lag behind the latest

How Execution Works

Here is a summary of how C# code actually runs. Understanding this makes error messages and performance discussions easier to follow.

C# is a compiled language, but rather than compiling directly to machine code, it goes through an intermediate code step — a two-stage process.

Source code (.cs file) csc (compiler) Intermediate code (IL) (.exe / .dll file) CLR (JIT compile) Machine code (executed directly by the CPU) CLR (Common Language Runtime) IL is OS-independent. The CLR converts it to machine code at runtime.

The role of IL and the CLR

The C# compiler (csc) converts source code into code called "IL (Intermediate Language)." IL is an intermediate format that is not tied to any specific CPU (Central Processing Unit — the processor that executes computations).

At runtime, the CLR (Common Language Runtime) JIT (Just-In-Time) compiles the IL into machine code on the fly and hands it to the CPU.

This mechanism allows the same IL file to run on Windows, Linux, and macOS (the same idea as Java bytecode + JVM (Java Virtual Machine — a virtual machine that runs Java bytecode)).

The Roslyn compiler

Since 2014, the C# compiler has been replaced by "Roslyn," an open-source compiler platform. Roslyn's distinguishing features are that the compiler itself is written in C#, and its internal APIs (syntax analysis, type checking, code generation) are designed to be accessible from external tools.

The real-time error detection, code completion, and refactoring suggestions you see in Visual Studio and VS Code are powered by calls to Roslyn's compiler APIs. Because the IDE and the compiler share the same code analysis engine, what you see in the editor matches the actual compilation result.

Actual execution steps

sample_hello.cs
using System;

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

Run the following command:

dotnet run
Hello, World!

Today, a single dotnet run command handles compilation and execution together. Internally, it automatically performs compile → IL generation → CLR execution.

AOT compilation — an ahead-of-time alternative

In addition to JIT compilation (converting to machine code at runtime), .NET 7 and later also offer AOT (Ahead-Of-Time) compilation. AOT compilation converts code to machine code at build time, resulting in faster startup.

JIT compilation can optimize code by observing how it is actually used during execution, so it excels in long-running server applications. AOT compilation, on the other hand, is well-suited for command-line tools and mobile apps where startup speed matters most.

Variables and Types

Because C# is statically typed, you specify a type when declaring a variable.

Basic types

Examples of declaring the most common types in C#.

string name = "item_b2"; // string
int count = 20; // integer
double rate = 3.5; // decimal number
bool isActive = true; // boolean

var — type inference

Using var lets the compiler infer the type from the right-hand side. The type is not omitted — the compiler determines it automatically.

var name = "item_b2"; // inferred as string
var count = 20; // inferred as int
var rate = 3.5; // inferred as double

Common types

TypeDescriptionExample
int32-bit integer42, -10
long64-bit integer (large numbers)9_999_999_999L
double64-bit floating-point number3.14
float32-bit floating-point number3.14f
decimalHigh-precision decimal (for monetary values)9.99m
boolBoolean valuetrue, false
charSingle character'A'
stringString"Hello"
objectThe base type of all typesAccepts any value

Classes and Objects

C# is an object-oriented language. You define a "class" that bundles data and behavior together, then create "objects (instances)" from that class to use them.

Defining a class and creating instances

Define a class, create an instance, and call a method.

class Member {
    public string Name;
    public int Score;

    public void Report() {
        Console.WriteLine(Name + " score: " + Score);
    }
}

Member member = new Member();
member.Name = "item_b2";
member.Score = 28;
member.Report();
item_b2 score: 28

Constructor

A constructor is an initialization method called automatically when an instance is created.

class Member {
    public string Name;
    public int Score;

    // Constructor
    public Member(string name, int coeff) {
        Name = name;
        Score = coeff;
    }

    public void Report() {
        Console.WriteLine(Name + " score: " + Score);
    }
}

var member = new Member("item_b2", 28);
member.Report();
item_b2 score: 28

For details on classes, inheritance, and interfaces, see pages such as IEnumerable / IList.

Collections — List and Dictionary

Here are the basics of the most commonly used collections in C#.

List<T> — a resizable array

List<T> is an array that lets you freely add and remove elements. Replace T with the type you want to store.

var names = new List<string>();
names.Add("item_a1");
names.Add("item_b2");
names.Add("item_a3");

Console.WriteLine(names.Count); // 3
Console.WriteLine(names[0]); // item_a1
3
item_a1

Dictionary<TKey, TValue> — key-value pairs

Dictionary<TKey, TValue> is a collection that stores key-value pairs.

var scores = new Dictionary<string, int>();
scores["item_a1"] = 78;
scores["item_b2"] = 28;
scores["item_c4"] = 44;

Console.WriteLine(scores["item_b2"]); // 28
28

For the methods of List and Dictionary, see List.Add() / Remove() / Clear() and Dictionary.Add() / Remove() / Clear().

String Operations

C#'s string type comes with a rich set of methods.

string s = "item_a1";

Console.WriteLine(s.Length); // 7
Console.WriteLine(s.ToUpper()); // ITEM_A1
Console.WriteLine(s.Contains("_a")); // True
Console.WriteLine(s.Replace("_a1", "_x1")); // item_x1

// String interpolation
int score = 78;
string message = $"{s}'s score is {score}.";
Console.WriteLine(message);
7
ITEM_A1
True
item_x1
item_a1's score is 78.

$"..." is string interpolation, which lets you embed variable values using {variable} (C# 6 and later).

C#'s string is immutable. Methods like Replace() and ToUpper() do not modify the original string; they return a new string object. When performing many string concatenations in a loop, using StringBuilder reduces the number of memory allocations.

For the individual string methods, see string.Length / IndexOf() and related pages.

LINQ — Collection Operations

LINQ (Language Integrated Query) is a feature that lets you filter, transform, and aggregate collections and data sources with a unified syntax. Add using System.Linq; to use it.

using System.Linq;

var people = new List<string> {
    "item_a1",
    "item_b2",
    "item_a3",
    "item_c4",
    "item_a5"
};

// Get items containing "a"
var filtered = people.Where(p => p.Contains("a")).ToList();

foreach (var name in filtered) {
    Console.WriteLine(name);
}
item_a1
item_a3
item_a5

Commonly used LINQ methods

MethodDescription
Where()Filter by condition
Select()Transform each element into a new sequence
OrderBy() / OrderByDescending()Sort in ascending / descending order
Count()Return the number of elements
Sum() / Average()Calculate sum / average
First() / Last()Return the first / last element
Any() / All()Check whether any / all elements satisfy a condition
ToList() / ToArray()Convert the result to a List or array

For details on each LINQ method, see Enumerable.Where() and related pages.

Exception Handling

Exception handling lets you respond to unexpected errors. C# uses try-catch-finally.

try {
    int[] arr = { 1, 2, 3 };
    Console.WriteLine(arr[5]); // out-of-range access
}
catch (IndexOutOfRangeException ex) {
    Console.WriteLine("Error: " + ex.Message);
}
finally {
    Console.WriteLine("Always executed");
}
Error: Index was outside the bounds of the array.
Always executed

Write the risky code in the try block, catch the exception in catch, and handle it there. The finally block always runs regardless of whether an exception occurred (use it for closing files or releasing resources).

For details, see try-catch-finally.

File I/O

File reading and writing is done with the File class and StreamReader / StreamWriter.

File.WriteAllText / File.ReadAllText

A sample showing simple file writing and reading.

using System.IO;

// Write to a file (overwrites existing content)
File.WriteAllText("log.txt", "item_c4 score: 44");

// Read from a file
string content = File.ReadAllText("log.txt");
Console.WriteLine(content);
item_c4 score: 44

File.WriteAllText is well-suited for writing short text. For large files, StreamWriter is more appropriate.

For details on file I/O, see File.ReadAllText() / WriteAllText().

Asynchronous Processing — async/await

When performing time-consuming operations such as file I/O or HTTP requests asynchronously, use async and await (C# 5 and later).

using System.IO;
using System.Threading.Tasks;

static async Task<string> ReadFileAsync(string path) {
    string content = await File.ReadAllTextAsync(path);
    return content;
}

An operation marked with await "releases the thread while waiting for completion and lets other work proceed." When the operation finishes, execution resumes from the line after await.

Synchronous vs. asynchronous comparison

SynchronousAsynchronous (async/await)
Code complexitySimpleRequires understanding async/await
Thread while waitingBlockedReleased for other work
Web app throughputLow (thread occupied while waiting)High (thread can handle other requests while waiting)
Suited forCPU work / short operationsI/O operations (file / HTTP / DB)

For details on asynchronous processing, see async / await.

Nullable Types and Null-Coalescing Operator

In C#, types such as string and int normally cannot hold null. To allow null, append ? to the type name.

string name = null; // Warning in C# 8+ (when nullable reference types are enabled)
string? name2 = null; // Explicitly allows null

int count = null; // Error: int cannot be null
int? count2 = null; // OK: nullable int

Null-coalescing operator ??

The ?? operator uses the right-hand value only when the left-hand side is null.

string? inspector = null;
string result = inspector ?? "item_b2";
Console.WriteLine(result); // item_b2
item_b2

For nullable types, see nullable. For the null-coalescing operator, see null-coalescing operator.

Properties

In C# classes, rather than giving direct access to fields, it is standard practice to expose them through "properties."

class Member {
    // Properties (with get and set)
    public string Name { get; set; }
    public int Score { get; private set; } // read-only from outside

    public Member(string name, int coeff) {
        Name = name;
        Score = coeff;
    }
}

var member = new Member("item_a5", 225);
Console.WriteLine(member.Name); // item_a5
Console.WriteLine(member.Score); // 225

member.Name = "item_c4"; // OK
// member.Score = 300; // Error: private set
item_a5
225

The { get; set; } syntax is called an "auto-implemented property." The compiler automatically generates the backing field.

Development Tools and Ecosystem

Here is an overview of the main development tools and package management system for C#.

IDEs — Visual Studio and Visual Studio Code

The most widely used IDE for C# development is Visual Studio. As Microsoft's own integrated development environment, it combines code completion, debugger, profiler, and test runner into a single tool. The Community Edition (for individuals and small teams) is free on Windows and includes all the essential features for C# development.

For a lighter editor, Visual Studio Code (VS Code) also supports C# development. Installing the C# Dev Kit extension provides code completion, debugging, and test execution. Since VS Code runs cross-platform, it is a good choice for writing C# on Linux or macOS.

Beyond these, JetBrains' Rider (paid) also enjoys strong popularity.

NuGet — package management

The package management system for C# / .NET is NuGet (pronounced "new-get"). It is the equivalent of npm for JavaScript or pip for Python, handling library downloads, version management, and dependency resolution.

dotnet add package Newtonsoft.Json

This command adds Newtonsoft.Json, a JSON processing library, to the project. Package information is recorded in the project file (.csproj), so team members automatically install the same packages.

dotnet CLI — command-line tool

The dotnet command included with the .NET SDK covers a wide range of operations, from creating projects to building, testing, running, and managing packages.

CommandDescription
dotnet new consoleCreate a new console application project
dotnet buildBuild the project
dotnet runBuild and run
dotnet testRun tests
dotnet add package [name]Add a NuGet package
dotnet publishPackage for deployment

Even without an IDE, you can develop C# with just a text editor and a terminal.

Testing frameworks

C# has several testing frameworks available. The three main choices are MSTest (Microsoft's own), xUnit (widely used within the .NET team), and NUnit (evolved from a port of JUnit). All three can be run with the dotnet test command and integrate with Visual Studio's Test Explorer and CI/CD (Continuous Integration / Continuous Delivery — a system that automatically builds, tests, and deploys code changes) pipelines.

using Xunit;

public class CalculatorTest {
    [Fact]
    public void Add_TwoNumbers_ReturnsSum() {
        var result = 2 + 3;
        Assert.Equal(5, result);
    }
}

Testing is not a language feature per se, but it is knowledge you will almost certainly need when using C# in practice.

Common Errors and Solutions

NullReferenceException — null reference error

This is one of the most common errors. It occurs when you try to access a method or property on a null object.

string name = null;
Console.WriteLine(name.Length); // NullReferenceException

Solution: Perform a null check before accessing, or use the null-conditional operator ?..

string? name = null;

// null check
if (name != null) {
    Console.WriteLine(name.Length);
}

// Null-conditional operator (returns null if name is null)
Console.WriteLine(name?.Length);

IndexOutOfRangeException — out-of-range array access

This occurs when you access an index that does not exist in an array or list.

var names = new List<string> { "item_x", "item_y" };
Console.WriteLine(names[5]); // IndexOutOfRangeException

Solution: Check the number of elements with Count before accessing.

InvalidCastException — type conversion error

This occurs when you try to cast to an incompatible type.

object obj = "item_a3";
int num = (int)obj; // InvalidCastException

Solution: Check the type with is before casting, or use the as operator which returns null on failure instead of throwing.

object obj = "item_a3";

if (obj is string s) {
    Console.WriteLine(s.Length); // safe
}

For details on type checking and conversion, see is / as / pattern matching.

How to Write Comments

Comment syntax in C#. Comments have no effect on how code runs — they are used to communicate intent or to temporarily disable code (commenting out).

Types of Comments

TypeSyntaxOverview
Single-line comment// textEverything from // to the end of the line becomes a comment. Also used inline after a statement.
Block comment/* text */Comments spanning multiple lines. Cannot be nested.
XML documentation comment/// textA comment starting with ///, written immediately before a class, method, or property. IDEs parse these as documentation and display them in tooltips.

Sample

A sample demonstrating all three comment styles.

int score = 100; // Inline comment — used to add a short note after a statement.

/*
  Block comment: everything between /* and */ is a comment.
  Use this when you need to write explanations spanning multiple lines.
*/

/// <summary>
/// XML documentation comment: starts with ///.
/// Written immediately before a class, method, or property.
/// </summary>
/// <param name="x">Input value</param>
/// <returns>Calculation result</returns>
int Calculate(int x) {
	return x * 2;
}

Comments can hold whatever you find useful. Common uses include why the code is written a certain way, what the code does, TODOs, and notes — but you are free to write whatever fits the situation. For the full list of XML documentation tags, guidelines on when to comment, and real-world conventions, see the comment reference page.

Recommended Learning Order

Here is a recommended order for learning C# features efficiently. Each item links to the corresponding dictionary page. The order is arranged so that each step builds on the previous one with minimal prerequisites.

Step 1 — Setup and first steps

Start by preparing an environment where C# runs, then execute a single-line program.

Step 2 — Variables, basic types, and operators

Learn how to declare variables that hold values, and the operators that combine them.

Step 3 — Control flow (branching and loops)

These structures branch and repeat the flow of your program. Once you master them, the range of programs you can write expands dramatically.

Step 4 — String operations

Strings are among the most frequently handled types of data. Take a tour of the built-in string methods.

Step 5 — Numbers and conversion

Move between strings and numbers, and perform mathematical calculations.

Step 6 — Arrays and collections

Data structures for handling multiple values together. C# provides several collection types so you can pick the right one for each use case.

Step 7 — Date and time

Dates and times come up in both business applications and games.

Step 8 — Classes and object orientation

The mechanism for bundling data and behavior. From here on, C#'s distinctive flavor comes through.

Step 9 — Null safety

Mechanisms to avoid the frequently occurring NullReferenceException.

Step 10 — Exception handling

The constructs used to deal with unexpected errors.

Step 11 — LINQ

One of C#'s signature features, letting you operate on collections with a SQL-like unified syntax.

Step 12 — File and directory operations

File I/O is a fundamental part of most programs. C# offers different tools for short text and larger files.

Step 13 — Asynchronous processing

Mechanisms for efficiently handling operations with waiting time, such as files, networks, and databases.

Step 14 — Unity / common APIs for game development

When using C# for game development with Unity, you will frequently encounter the following APIs (Application Programming Interface — an interface for software components to communicate). Feel free to skip this step if you are not using Unity.

Steps 1 through 3 alone are enough to write programs that receive input, branch on conditions, loop, and produce output. Pages for web, business applications, and games are each independently accessible.

Summary

C# is a statically typed, object-oriented language designed by Anders Hejlsberg and released by Microsoft in 2002. It runs on the .NET platform and covers a wide range of use cases including web applications, Windows desktop software, and game development (Unity).

Born out of the Java license dispute in the late 1990s, C# was designed to fuse the strengths of C++, Java, and Delphi. Since 2014, the open-sourcing and cross-platform expansion of .NET has extended C#'s reach well beyond Windows.

The compilation flow is: .cs file → csc compiler → IL (intermediate code) → CLR (JIT) → machine code execution. Because IL is OS-independent, the same code runs on Windows, Linux, and macOS. Starting with .NET 7, AOT (ahead-of-time) compilation is also available for use cases where startup speed matters.

C# key features summary

Static typing

  • Explicit types for variables, parameters, and return values
  • var enables type inference
  • Nullable types (string?) make null-safety explicit

Collections

  • List<T> — resizable array
  • Dictionary<TKey, TValue> — key-value pairs
  • LINQ — filter, transform, and aggregate collections with a unified syntax

Async and exceptions

  • async / await — perform I/O operations asynchronously
  • try-catch-finally — catch exceptions and handle them safely

What you gain by using C#

  • Type-mismatch bugs caught before compilation
  • Accurate IDE autocompletion that reduces typos in property names
  • Concise collection operations with LINQ
  • Skills that map directly to Unity development

What increases when using C#

  • More code to write due to type declarations
  • A compilation step is required (automated by dotnet run)
  • Dependency on the .NET ecosystem

Mastering the basic types string / int / bool and List<T> is enough to write a wide variety of programs.

C# today

More than 20 years after its debut in 2002, C# continues to thrive. Microsoft's push for open-source .NET and cross-platform support has expanded C#'s reach far beyond Windows — Unity game development, ASP.NET Core web backends, and .NET MAUI mobile apps cover an ever-growing range of domains.

Its designer, Anders Hejlsberg, is the person behind four language systems: Turbo Pascal, Delphi, C#, and TypeScript. C#'s design carries the deep imprint of Hejlsberg's accumulated experience — the importance of compilation speed, the pursuit of developer experience, and a commitment to putting practicality first.

The reason C# has continued to evolve for over two decades lies in its flexible design policy of actively adopting the best ideas from other languages. LINQ drew from SQL, async/await from F#'s asynchronous workflows, and pattern matching from functional languages. Rather than insisting on originality, C# takes good ideas regardless of where they come from and reshapes them to fit naturally within its own context. This willingness to adapt is a defining characteristic of the language.

If you find any errors or copyright issues, please .