Biến cục bộ (Local Variables)
Phạm vi trong method/block khai báo. Chỉ truy cập được bên trong hàm đó.
Ví dụ
using System;
public class Program
{
public static void Main()
{
int a = 100; // biến cục bộ
Console.WriteLine("Giá trị: " + a);
}
}
Kết quả
Giá trị: 100
Biến toàn cục (Global Variables)
C# không hỗ trợ biến toàn cục trực tiếp
Best practice: Tránh trạng thái toàn cục, dùng Dependency Injection, Singleton pattern, hoặc static class cho shared state.
static field trong class để chia sẻ dữ liệu:: dùng cho namespace alias: global::System.ConsoleVí dụ namespace alias
using myAlias = System.Collections;
namespace Program
{
class Demo
{
static void Main()
{
myAlias::Hashtable hTable = new myAlias::Hashtable();
hTable.Add("A", "1");
// ...
foreach (string str in hTable.Keys)
{
global::System.Console.WriteLine(str + " " + hTable[str]);
}
}
}
}