본문으로 바로가기

const 와 readonly 그리고 enum

category Development/C# 2009. 11. 10. 19:01
C#에는 const, readonly 그리고 enum 등의 세 가지 상수가 있다.
이 중에서 const와 readonly는 값을 변경할 수 없는 변수와 같으며 enum은 이름을 가지는 정수형 상수라 할 수 있다.

const, readonly
const는 변수의 정의와 함께 초기화되어야 하는 상수이고 readonly는 추가적으로 클래스의 static 생성자에서 초기화할 수 있는 상수이다.
말 그대로 상수이므로 두 번 이상의 초기화는 할 수 없다.

using System;  
 
class ConstReadonlyTest{  
    // const 상수는 반드시 정의와 함께 초기화되어야 하며 그 값은 변경이  
    // 불가능하다. const는 자동으로 static 변수로 선언된다.  

    public const string cnst = "Hi";  
 
    // readonly 상수도 const와 같이 정의와 함께 초기화할 *수도* 있으나  
    // 자동으로 static 멤버가 되지는 않는다. static이 아닌 readonly 상수는  
    // 반드시 정의와 함께 초기화되어야 한다.  

    public readonly int rdonly = 2;  
 
    // readonly 상수는 static 키워드를 이용해서 직접 static으로 만들 수  
    // 있다. 초기화하지 않을 경우 0이 할당된다.  

    public static readonly int rdonly2;  
 
    // static readonly 상수의 초기화는 static 생성자에서만 가능하다.  
    public static readonly int rdonly3;  
 
    // static 생성자는 public 또는 private으로 선언할 수 없으며 인스턴스  
    // 생성시가 아닌 클래스 참조시에 실행된다.  

    static ConstReadonlyTest(){  
        rdonly3 = 3;  
    }  
}  
 
class ConstReadonlyExample{  
    public static void Main(){  
        // cnst는 static 멤버이다.  
        Console.WriteLine(ConstReadonlyTest.cnst);  
 
        Console.WriteLine(ConstReadonlyTest.rdonly2);  
        Console.WriteLine(ConstReadonlyTest.rdonly3);  
 
        ConstReadonlyTest test = new ConstReadonlyTest();  
        Console.WriteLine(test.rdonly);  
    }  
}


enum

enum은 이름을 가지는 열거형 상수이다.

using System;  
 
class EnumExample{  
    // enum은 반드시 메서드 밖에서 정의해야 한다.  
    enum Number{zero, two=2, three, four}  
    public static void Main(){  
        // i는 Number enum에서 정의하지 않은 1의 값을 가질 수 있다.  
        for(Number i=Number.zero; i<=Number.four; i++)  
            Console.Write(i+"="+(int)i+"\t");  
        Console.Write("\n");  
 
        for(int j=0; j<=4; j++)  
            // int형인 j를 Number enum으로 캐스팅할 수 있다.  
            Console.Write((Number)j+"="+j+"\t");  
        Console.Write("\n");  
    }  

상수 라고 해서 의미는 비슷할 지 모르나, 분명히 목적에 따라 다르게 쓰이는 것 같다.

사용 시 용도를 따지는 습관을 갖자!!

'Development > C#' 카테고리의 다른 글

ThreadPool을 이용한 순차적 실행  (0) 2009.11.24
Threading.Timer  (0) 2009.11.17
MS Chart Control  (2) 2009.11.03
zedgraph  (0) 2009.11.02
알람소리 내기  (0) 2009.10.29