Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hệ thống kiểu & Generics

Generics

// Generic class
public class Repository<T> where T : class
{
    private List<T> _items = new List<T>();
    
    public void Add(T item)
    {
        _items.Add(item);
    }
    
    public T GetById(int id)
    {
        // Implementation
        return default(T);
    }
}

// Generic method
public T Max<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b) > 0 ? a : b;
}

// Sử dụng
var repo = new Repository<Product>();
repo.Add(new Product());

int max = Max(10, 20); // 20

Nullable Types

// Nullable value types
int? nullableInt = null;
DateTime? nullableDate = null;

if (nullableInt.HasValue)
{
    int value = nullableInt.Value;
}

// Null-coalescing operator
int safeValue = nullableInt ?? 0;

// Null-conditional operator
string name = person?.Name?.ToUpper() ?? "Unknown";

// Null-forgiving operator (C# 8+)
string notNull = possiblyNull!; // Assert not null

Type Conversion

// Implicit conversion
int small = 10;
long large = small; // OK

// Explicit conversion (cast)
double d = 9.8;
int i = (int)d; // 9

// as operator (returns null if fails)
object obj = "Hello";
string str = obj as string; // "Hello"
int? number = obj as int?; // null

// is operator
if (obj is string)
{
    Console.WriteLine("It's a string");
}

// Pattern matching with is
if (obj is string s)
{
    Console.WriteLine($"Length: {s.Length}");
}

Boxing và Unboxing

// Boxing - value type → reference type
int value = 42;
object boxed = value; // Boxing

// Unboxing - reference type → value type
int unboxed = (int)boxed; // Unboxing

// Performance impact
// Boxing allocates memory on heap
// Unboxing requires type check and copy