C#문법

[C# 문법] Part19 프로퍼티(Property)

BlackWolfDev 2025. 2. 2. 23:42

[ 개요 ]

C#의 핵심 기능 중 하나인 프로퍼티(Property)에 대해 자세히 알아보자.


[ Property란? ]

프로퍼티는 필드(변수)에 대한 접근을 제어하는 방법을 제공하는 멤버이다.

겉으로 보기에는 필드처럼 보이지만, 실제로는 메서드처럼 동작하여 데이터의 유효성 검사나 계산된 값을 반환할 수 있다.

get set 문법을 사용한다.


[ Property 기본 문법 ]

public class Player
{
    // 백킹 필드 (backing field)
    private int health;

    // 기본적인 프로퍼티 구현
    public int Health
    {
        get { return health; }
        set 
        { 
            if (value < 0)
                health = 0;
            else if (value > 100)
                health = 100;
            else
                health = value;
        }
    }
}

[ Property의 종류 ]

1. 전체 프로퍼티 (Full Property)

public class Character
{
    private string characterName;
    private int level;

    public string Name
    {
        get { return characterName; }
        set { characterName = value; }
    }

    public int Level
    {
        get { return level; }
        set 
        {
            if (value >= 1 && value <= 99)
                level = value;
        }
    }
}

 

2. 자동 구현 프로퍼티 (Auto-Implemented Property)

public class Weapon
{
    // 컴파일러가 자동으로 백킹 필드를 생성
    public string Name { get; set; }
    public int Damage { get; set; }
    public float Weight { get; private set; } // 읽기 전용
}

 

3. 읽기 전용 프로퍼티 (Read-Only Property)

public class Enemy
{
    private readonly int maxHealth = 100;
    
    // 읽기 전용 전체 프로퍼티
    public int MaxHealth
    {
        get { return maxHealth; }
    }

    // 읽기 전용 자동 구현 프로퍼티
    public string EnemyType { get; }

    // 계산된 읽기 전용 프로퍼티
    public bool IsAlive
    {
        get { return CurrentHealth > 0; }
    }
}

[ Property의 장점 ]

  1. 캡슐화 강화
  2. 유효성 검사
  3. 데이터 변경 추적

[ Property 사용 시 주의사항 ]

 

  1. 과도한 로직 지양
  2. getter에서 예외 발생 피하기
  3. setter에서 예상치 못한 부작용 피하기

 

728x90
반응형