Search code examples
c#.netencapsulation

Is it good exapmple of encapsulation in C# ? Or should i use public set; get;?


I want to write a person class. I am not sure when should I use public set on a property.

In the following example, should I use public set on Name property ?

class Person
{
    public string Name { get; private set; }
    public DateTime DateOfBirth { get; private set; }
    public Person[] Parents 
    { 
        get { return (Person[])Parents.Clone(); }
        private set { Parents = value; } 
    }

    public Person(string Name, DateTime DateOfBirth, Person[] parents=null)
    {
        this.Name = Name;
        this.DateOfBirth = DateOfBirth;
        Parents = parents;
    }
}

Solution

  • If you want to able to change the property from a code which relies outside the class - yes.

    class program
    {
        public void main()
        {
           Person p = new Person("New Born", DateTime.Now());
           :
           :
           p.Name="John";
        }
    }
    

    However, if the name should never change from the outside and only from within the class code - no.

    As a general guideline:

    If the property setter is public,
    - You usually don't need to add a constructor parameter to force setting it.

    If you do wish for some reason to force setting it,
    - it probably don't need to be public.

    But that's just a general guideline - not a "strong" rule.