본문 바로가기
개발/기본) 기본기

기본기)c#) 자동으로 구현된 속성

by 테샤르 2022. 2. 11.

 자동으로 구현된 속성

 

C# 3.0 이상부터는 자동으로 속성을 구현이 가능하다.

예전에는 get, set을 메서드를 따로 구성해주곤 했는데

C# 9 이상부터는 init 접근자를 자동으로 구현 속성으로 선언이 가능하다.

struct Point
{
    public int X { get; init; }
    public int Y { get; init; }
}


var p = new Point() { X = 42, Y = 13 };

 

다양한 형태로 속성을 처리할 수 있다.

public class DateClass
{
    private int year {get;private set;}
    private int _month = -1;  // Backing store

    public int Month
    {
        get => _month;
        set
        {
            if ((value > 0) && (value < 13))
            {
                _month = value;
            }
        }
    }
    
    public DateClass(int _year){
    	year = year,
	}
 
}

개인적으로는 좀더 편리해진 형태로 따로 값을 처리 안 해줘도 되는 이점이 있다.

꼭 사용은 안하더라도 사용방법에 대해서는 숙지는 하는 게 좋아 보인다.

 

반응형

Microsoft Docs : [링크]

 

Init only setters - C# 9.0 specification proposals

초기화 전용 SetterInit Only Setters 이 문서의 내용 --> 요약Summary 이 제안서는 init only 속성 및 인덱서의 개념을 c #에 추가 합니다.This proposal adds the concept of init only properties and indexers to C#. 이러한 속성

docs.microsoft.com

 

★☆☆☆☆

 

반응형

댓글