Lập trình hướng đối tượng C#

Generics

Generics preserve concrete type information without duplicating implementation.

How it works

Write reusable, type-safe classes and methods.

Box<T> can store any chosen type while preventing values of other types from being assigned accidentally.

Runnable C# example

C#
Run code →
Program.cs
using System;

class Box<T>(T value) { public T Value { get; } = value; }

class Program
{
    static void Main()
    {
        var box = new Box<int>(42);
        Console.WriteLine(box.Value);
    }
}
Expected output
42

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.