상세 컨텐츠

본문 제목

프로퍼티(property)

C#

by MJ_119 2024. 6. 21. 13:17

본문

프로퍼티

  • get: 프로퍼티 값을 읽을 때 호출됩니다.
  • set: 프로퍼티 값을 쓸 때 호출됩니다.
public class Person
{
    private string name; // 백킹 필드

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

 

public class Person
{
    public string Name { get; set; }
}

 

public class Person
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value < 0)
                throw new ArgumentException("Age cannot be negative");
            age = value;
        }
    }
}

 

 

'C#' 카테고리의 다른 글

Action Func  (0) 2024.06.21
인터페이스(interface)  (0) 2024.06.21
델리게이트, 이벤트  (0) 2024.06.20
구조체(Struct), 열거형(enum)  (0) 2024.06.19
arrayList, List, Hashtable, Dictionary, Queue, Stack  (0) 2024.06.19

관련글 더보기