Please explain how C# properties work?

前端 未结 4 1923
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 05:51

I\'ve been learning C# for a while now, and I\'ve come across properties in my C# book (Head First C#). I honestly do not understand what they\'re used for, and why I should

4条回答
  •  盖世英雄少女心
    2020-12-10 06:36

    Properties are used to enrich the Encapsulation concept of Object-Oriented Programming.

    i.e. They encapsulate a field-member and let you (the developer) control how setting/getting this variable is done. Example?

    public class Person
    {
        private int m_age;
    
        public int Age
        {
            set
            {
                if(value < 18)
                    m_age = 18;
                else
                    m_age = value;
            }
            get
            {
                return m_age;
            }
        }
    }
    

    See? using property Age, we guaranteed that the minimum set value of age is 18.

提交回复
热议问题