C#의 Expression-Bodied Member(줄여서 “Body Expression” 또는 “화살표 멤버”)는, 짧은 메서드나 프로퍼티 등을 한 줄로 표현할 때 유용한 문법. => 연산자를 사용해서, { … } 블록을 없애고 곧바로 식(Expression)을 리턴하거나 실행하도록 만든다.
// 기존 메서드
public int Square(int x)
{
return x * x;
}
// Expression-Bodied 버전
public int Square(int x) => x * x;
=> 식; 형태로, 식의 결과가 리턴
반환 타입이 void인 경우에도 사용 가능
// 기존
public void Log(string msg)
{
Console.WriteLine(msg);
}
// 축약
public void Log(string msg) => Console.WriteLine(msg);
| 대상 | 문법 예시 |
|---|---|
| 메서드 | int Foo() => 42; |
| 프로퍼티 | public string Name => _name; |
| 프로퍼티 접근자 | get => …; / set => …; |
| 인덱서 | public T this[int i] { get => …; set => …; } |
| 생성자 / 소멸자 | public MyClass() => Initialize(); |
| 연산자 오버로드 | public static MyClass operator +(MyClass a, MyClass b) => …; |
public class PlayerStats : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
// 살아있는지 체크
public bool IsAlive => currentHealth > 0;
// 체력 비율
public float HealthRatio => (float)currentHealth / maxHealth;
}
IsAlive, HealthRatio 같은 계산형 프로퍼티를 한 줄로 정의.public class InputListener : MonoBehaviour
{
void OnEnable() => InputManager.OnJump += HandleJump;
void OnDisable() => InputManager.OnJump -= HandleJump;
void HandleJump() => Debug.Log("점프!");
}
OnEnable/OnDisable에서 이벤트 바인딩을 매우 간결하게.