📕프로퍼티(Property, 속성)
프로퍼티는 클래스에 속한 멤버로, 필드를 상황에 따라 유연하게 읽고 쓰고 싶을 때 사용하는 메서드이다. 프로퍼티를 사용하면 읽기 전용 필드와 쓰기 전용 필드를 만들 수 있다. 또한 읽기와 쓰기 둘 다 가능한 필드를 만드는 것도 가능하다. 즉, private으로 선언한 필드에 대한 접근 권한을 읽기와 쓰기로 나누어 허용하거나 제한할 수 있다는 얘기다. 이를 잘 활용하면 데이터의 접근성과 안전성을 동시에 높일 수 있다.
프로퍼티의 기본 형태는 다음과 같다.
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
Person 클래스 내에 string 형식의 필드와 프로퍼티를 선언했다. 일반적으로 프로퍼티의 이름은 필드의 이름을 그대로 사용하되 첫 글자는 대문자로 쓴다. 위 코드에서도 필드 이름은 'name'으로, 프로퍼티 이름은 'Name'으로 지은 것을 볼 수 있다.
프로퍼티는 쉽게 말해 get 메서드와 set 메서드의 조합이다. get에는 외부에 값을 반환하는 return문이 있고 set에는 외부 값을 받아오는 예약어 value가 있다. 사용자는 get과 set 중 하나만 쓸 수도 있고 둘 다 쓸 수도 있다. get만 쓴다면 읽기 전용 프로퍼티가 되고 set만 쓴다면 쓰기 전용 프로퍼티가 된다. 위 예는 읽기와 쓰기 둘 다 가능한 프로퍼티이다.
프로퍼티에 접근할 때는 다음처럼 할 수 있다.
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
출력 결과: Liam
속성에 접근하는 방법은 필드에 접근하는 방법과 같다. 다만 필드와 다르게 속성에는 속성에 접근하거나 할당할 때 실행할 구문을 작성할 수 있다. 다음은 프로퍼티의 get과 set에 구문을 작성한 예이다.
using System;
class TimePeriod
{
private double _seconds;
public double Hours
{
get { return _seconds / 3600; }
set {
if (value < 0 || value > 24)
throw new ArgumentOutOfRangeException(
$"{nameof(value)} must be between 0 and 24.");
_seconds = value * 3600;
}
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// The property assignment causes the 'set' accessor to be called.
t.Hours = 24;
// Retrieving the property causes the 'get' accessor to be called.
Console.WriteLine($"Time in hours: {t.Hours}");
}
}
// The example displays the following output:
// Time in hours: 24
📌자동 구현 프로퍼티(Automatic Properties)
get과 set에 별다른 구문을 작성하지 않는다면 .NET 프레임워크에서 제공하는 자동 구현 프로퍼티로 간단하게 프로퍼티를 구현할 수 있다.
class Person
{
public string Name // property
{ get; set; }
}
/*class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}*/
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
출력 결과: Liam
자동 구현 프로퍼티를 사용하면 필드를 선언하지 않아도 되며 get과 set에 코드를 작성하지 않아도 된다. 길이가 짧아졌다는 점만 빼면 주석 처리한 기존 코드와 완전히 같다.
📌람다 연산자를 사용한 프로퍼티 선언
프로퍼티를 선언할 때 람다 연산자 '=>'를 사용하면 좀 더 간략하게 표현할 수 있다.
// 기존 표현
public int Area
{
get
{
return Height * Width;
}
}
// 람다 연산자를 사용한 표현
public int Area => Height * Width;
자동 구현 프로퍼티와 다른 점은 get과 set 안에 구문을 작성할 수 있다는 것이다.
💡이처럼 클래스나 구조체의 멤버를 간단하게 표현하는 방식을 '식 본문 정의(Expression body definitions)'라고 한다. 람다 식과 같은 연산자를 사용하기 때문에 식 본문 정의와 람다 식을 헷갈릴 수 있는데, MSDN에서는 람다 식과 식 본문 정의를 구분하고 있다.
The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition.
🔖인용한 사이트
C# 속성
유효성 검사, 계산된 값, 지연 평가, 속성 변경 알림 기능을 포함하는 C# 속성에 대해 알아봅니다.
docs.microsoft.com
C# Properties (Get and Set) (w3schools.com)
C# Properties (Get and Set)
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
C# 6.0 Expression-bodied - C# 프로그래밍 배우기 (Learn C# Programming) (csharpstudy.com)
C# 6.0 Expression-bodied - C# 프로그래밍 배우기 (Learn C# Programming)
Expression-bodied member 사용 C#의 속성이나 메서드는 보통 여러 문장(statement)들로 구성된 블럭을 실행하게 된다. 하지만 속성이나 메서드의 Body 블럭이 간단한 경우, Statement Block을 사용하는 대신 간
www.csharpstudy.com
'C#' 카테고리의 다른 글
구조체(Struct)와 클래스(Class) (0) | 2022.06.17 |
---|---|
생성자 (0) | 2022.06.17 |
람다 식(Lambda Expression) (0) | 2022.06.12 |
델리게이트(Delegate, 대리자)와 이벤트(Event) (0) | 2022.06.10 |
Class (0) | 2022.03.18 |