C# 변수 범위(Scope) 이해: 클래스, 메서드, 블록 레벨
C# 변수 범위(Scope) 이해하기
이 가이드는 C#에서 변수 범위가 어떻게 작동하는지 클래스 레벨, 메서드 레벨, 블록 레벨 범위로 나누어 명확한 실전 예제와 함께 설명합니다.
변수 범위(Scope)는 코드 내에서 변수에 접근할 수 있는 위치를 결정합니다. C#에서는 세 가지 주요 범위를 접합니다.
- 클래스 레벨 범위 (Class-Level Scope)
- 메서드 레벨 범위 (Method-Level Scope)
- 블록 레벨 범위 (Block-Level Scope)
클래스 레벨 변수 범위
메서드나 생성자 밖, 클래스 내부에 선언된 변수는 필드(Field)이며 해당 클래스 모든 멤버에서 접근 가능. 이를 클래스 레벨 범위라 합니다.
using System;
namespace VariableScope {
class Program {
// 클래스 레벨 필드
string str = "Class Level";
public void Display() {
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
출력
Class Level
str은 필드이므로 Program 클래스 전체, Display 메서드에서 사용 가능.
중요: 인스턴스 필드는 인스턴스 사용 없이는 정적 메서드에서 접근 불가. 예:
static void Display2() {
// 컴파일 에러
Console.WriteLine(str);
}
메서드 레벨 변수 범위
메서드 내부에 선언된 변수는 해당 메서드 지역 변수(Local Variable)로, 정의한 메서드 밖에서 참조 불가. 메서드 레벨 범위.
using System;
namespace VariableScope {
class Program {
public void Method1() {
// 지역 변수
string str = "method level";
}
public void Method2() {
// 여기서 str 접근 시 에러
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Method2();
Console.ReadLine();
}
}
}
str을 Method2에서 사용 시 컴파일 에러:
Error CS0103: The name 'str' does not exist in the current context
반면 같은 메서드 내에서는 사용 가능:
using System;
namespace VariableScope {
class Program {
public void Display() {
string str = "inside method";
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
출력
inside method
블록 레벨 변수 범위
루프, if 문, 기타 중첩 범위 같은 블록 내 선언된 변수는 해당 블록 내부에서만 접근 가능. 블록 레벨 범위.
using System;
namespace VariableScope {
class Program {
public void Display() {
for (int i = 0; i <= 3; i++) {
// i는 이 for 루프 블록에 한정
}
// Console.WriteLine(i); // ❌ 컴파일 에러
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
루프 카운터 i는 루프 종료 후 참조 불가. 범위가 블록과 함께 끝나기 때문.