C#/C#200제

[C#] 6일차 - 33. 상수, const와 readonly

반나무 2021. 1. 21. 10:54

상수는 변하지 않는 값

const readonly
선언될 때 값이 할당됨 실행될 때 또는 객체가 생성자에 의해 초기화될 때 값이 할당됨
"Classname.VariableName"으로 사용해야함 "InstanceName.VarialeName"으로 사용해야함
컴파일시에 값이 결정됨 런타임 시에 값이 결정됨
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A033_ConstAndReadonly
{
    class ConstEx
    {
        public const int number = 3;
    }

    class ReadonlyEx
    {
        public readonly int number = 10;
        public ReadonlyEx()
        {
            number = 20;
        }
        public ReadonlyEx(int n)
        {
            number = n;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ConstEx.number); // const 사용

            ReadonlyEx inst1 = new ReadonlyEx(); // readonly 사용
            Console.WriteLine(inst1.number);

            ReadonlyEx inst2 = new ReadonlyEx(100); // readonly 사용
            Console.WriteLine(inst2.number);
        }
    }
}

반응형