티스토리 뷰

Code/C#

[C#] const vs readonly

Hide Code 2008. 2. 11. 02:41
const 대 readonly 비교

using System;

namespace Test
{
   class Program
   {
       static void Main(string[] args)
       {
           Some s1 = new Some();

           Console.WriteLine(Some.constField); // const : 항상 static
           Console.WriteLine(s1.readonlyField1);
           Console.WriteLine(s1.readonlyField2);

           Some s2 = new Some(5);
           Console.WriteLine(s2.readonlyField2);
       }
   }

   class Some
   {
       // const readonly 공통 : 클래스 밖에서 값을 바꿀 수 없음

       // const : 항상 static (static 키워드 쓰지 않음)
       // const : 항상 선언시 초기화해야함
       // const : 초기화하지 않으면 exception 발생
       public const int constField = 2;

       // readonly : 선언시 초기화 가능
       // readonly : constructor 이용한 초기화 가능
       // readonly : 초기화하지 않으면 0 값으로 초기화됨 (string 형은 null)
       public readonly int readonlyField1 = 3;
       public readonly int readonlyField2;

       public Some()
       {
           readonlyField2 = 4;
       }

       public Some(int other)
       {
           readonlyField2 = other;
       }
   }

   class Some2 : Some
   {
       public Some2(int other)
           : base(other) // 가능
       {
       }
   }

   class Some3 : Some
   {
       public Some3()
       {
           readonlyField2 = 7; // error 발생
       }
   }
}

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함