본문 바로가기

프로그래밍/C#

C# 프로퍼티(Properties) 사용법

C# 프로퍼티(Properties) 사용법에 대해 포스팅 하겠습니다.

C++ 에서는 함수에 값을 쓰거나 가져올때

Get과 Set함수를 사용하였습니다.

public class GetSet
{
    public:
        inline int GetCount() const { return m_count; }
        inline void SetCount(int count) { m_count = count; }

    private:
        int m_count;
};

C# 에서는 이렇게 귀찮게 함수를 만들지 않고도 쉽게 Get, Set 을 할 수 있도록

프로퍼티(Properties) 라는 기능을 만들었습니다.

기본 형식은 다음과 같습니다.

class UseProperties
{
    int GetSet
    {
        get;
        set;
    }
}

자 이제 변수에서 직접 값을 Get, Set 하겠습니다.

기본적으로 Set을 하기 위해서는 매개변수로 value 라는 키워드를 쓰게됩니다.

class UserProperties
{
   int count = 5;
   int GetSet
   {
       get
       {
           return count;
       }
       set
       {
           count = value;
       }
   }
   static void Main(string[] args)
   {
       UserProperties program = new UserProperties();
       Console.WriteLine(program.GetSet);
       program.GetSet = 7;
       Console.WriteLine(program.GetSet);
   }
}

Properties중 set만 비공개로 하고 싶을 경우에는 set 키워드 앞에 private을 붙여주시면 됩니다.

class UseProperties
{
    int GetSet
    {
        get;
        private set;
    }
}