Language/C#

[C#] const 와 readonly

마탁이 2020. 12. 23. 19:48

1. const와 readonly

 - 상수를 표현할 경우 C#에서는 const 와 readonly 라는 예약어를 통해 설정 가능하다.

 - 공통점

  > 모두 초기화 이후에는 값을 변경할 수 없다.

 - 차이점

  > const 는 선언할 때만 초기화 할 수 있다

  > readonly 는 선언할 때 또는 생성자에서 초기화 될 수 있다.

 - const 는 컴파일 타임 상수

   readonly 는 런타임 상수로 불리기도 한다.

using System;

namespace ConsoleApp
{
    class Program
    {
        public class Product
        {
            public const int ConstPrice = 1000;
            public readonly int ReadOnlyPrice;

            public Product()
            {
                this.ReadOnlyPrice = 2000; // 생성자에서 초기 값 설정(readonly)
            }

            public Product(int price)
            {
                this.ReadOnlyPrice = price; // 외부에서 받은 값으로 초기 값 설정(readonly)
            }
        }

        static void Main(string[] args)
        {
            // 상수 값 가져오기
            // 상수는 정적인 멤버이므로 객체를 생성할 필요 없다.
            Console.WriteLine("ConstPrice : {0}", Product.ConstPrice);

            // 기본 생성자로 설정된 값
            Product item1 = new Product();
            Console.WriteLine("new Product() : ReadOnlyPrice={0}", item1.ReadOnlyPrice);

            // 생성자에서 특정 값을 매개변수로 넣음
            Product item2 = new Product(3000);
            Console.WriteLine("new Product(3000) : ReadOnlyPrice={0}", item2.ReadOnlyPrice);
        }
    }
}

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

[C#] try ~ catch ~ finally, throw  (0) 2020.12.23
[C#] 박싱(Boxing)과 언박싱(Unboxing)  (0) 2020.12.23
[C#, 공통] 변수 및 함수 표기 방식  (0) 2020.12.23
[C#] struct, class의 참조 형식  (0) 2020.12.23
[C#] 튜플의 사용  (0) 2020.12.17