산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# 변수 범위(Scope) 이해: 클래스, 메서드, 블록 레벨

C# 변수 범위(Scope) 이해하기

이 가이드는 C#에서 변수 범위가 어떻게 작동하는지 클래스 레벨, 메서드 레벨, 블록 레벨 범위로 나누어 명확한 실전 예제와 함께 설명합니다.

변수 범위(Scope)는 코드 내에서 변수에 접근할 수 있는 위치를 결정합니다. C#에서는 세 가지 주요 범위를 접합니다.


클래스 레벨 변수 범위

메서드나 생성자 밖, 클래스 내부에 선언된 변수는 필드(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는 루프 종료 후 참조 불가. 범위가 블록과 함께 끝나기 때문.

C 언어

  1. 파이썬 global 키워드 마스터하기: 사용법과 타이밍
  2. C++ 포인터 완전 정복: 개념, 예제, 실전 활용
  3. C 변수, 데이터 타입, 상수 – 실전 가이드
  4. Verilog 할당문 이해: 유형, 문법, 모범 사례
  5. 게이트 레벨 모델링: 하드웨어 회로도에서 Verilog 코드로
  6. 모든 범위에서 Verilog Timescale 이해 및 출력하기
  7. Java 변수 타입 이해: 종합 가이드
  8. C 변수 완전 이해: 선언, 정의, 초기화, 저장 클래스, Lvalue/Rvalue
  9. C 스코프 규칙: 지역, 전역, 정적, 매개변수 변수의 가시성과 수명
  10. C 포인터 마스터: 기초부터 포인터 연산, 배열/함수 포인터, 동적 할당까지