Develop Dairy/C#

[Csharp] Readonly, const

개발자_옹이양 2021. 12. 30. 01:22

📖C# Readonly, Const

Readonly

  1. 읽기 전용 변수는 initializer, 생성자 메서드에 할당 가능
  2. 읽기 전용 변수는 여러번 재정의 가 가능하다.
public class Readonly
{
    private readonly ExampleObject _exampleObjecct = new ExampleObject() { Id = 1 };

    public Readonly()
    {
        // _exampleObjecct변수를 재정의 하는 모습
        _exampleObjecct = new ExampleObject( Id = 2);
        _exampleObjecct = new ExampleObject( Id = 3);
    }
}

public class ExampleObject
{
    public int id {get; set;}
}
  1. 메서드 밖에서는 재정의를 할 수 없음

Const

  1. const 변수 (상수)는 런타임에서 생성되기 때문에 참조를 할 수 없다. (재할당 불가 )

  2. 상수변수는 정적변수로 할 수 없다.

  3. 컴파일러는 IL 코드(중간 언어)를 생성할때 "const" 변수의 모든 참조를 해당 값으로 바꾼다.

  4. 사용

    public class ConstClass
    {
        private const string _constString = "const";
    
        public ConstClass()
        {
            Console.WriteLine(_constString);
        }
    }
  5. const가 참조된 변수들이 있다면 빌드를 다시 해야 함. (앱 버전이 바뀔때 라든가..)