// 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
// 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 - 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