C# Properties – Differences Between Private Property and Public Field

c

Will a private property same as a public field? Here is the sample code I wrote to understand this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetSet
{
    class Program
    {
        private int Age_private { get; set; }
        public int Age_public;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Age_public = 5;
            p.Age_private = 10;  // calling set
            int m = p.Age_public;
            int n = p.Age_private; // calling get
            Console.WriteLine(m);
            Console.WriteLine(n);
            Console.ReadLine();
        }
    }
}

Am I doing this correctly?

Also, does it follow that a public field will never require a getter and setter?

Reference: When are Getters and Setters Justified

Best Answer

Am I doing this correctly?

No. The idea of properties is that the property itself is public and provides access to private fields. Your example however does the opposit by declaring the property private while the field is exposed public.

What it should look like:

class Program
{
    private int Age_private;    //private field, not visible outside of class
    public int Age_public
    {      //public property to manage access to age
        get { return Age_private; }
        set
        {
            if (value == Age_private + 1)
            {
                Age_private = Age_private + 1;
            }
        }
    }
    public Program()
    {
        Age_private = 0;
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.Age_public = 1;     //increment age using setter
        int m = p.Age_public;        //get age from getter
        Console.WriteLine(m);
        p.Age_public = 2;     //increment age again using setter
        m = p.Age_public;
        Console.WriteLine(m);
        p.Age_public = 5;     //use setter with invalid value
        m = p.Age_public;
        Console.WriteLine(m);    //age is unchanged because setter didn't change the private field
        p.Age_public = -50;     //use setter with invalid value 
        m = p.Age_public;
        Console.WriteLine(m);    //age is still unchanged because setter didn't change the private field
        Console.ReadLine();
    }
}

DO NOT: expose fields outside of the class

DO: provide appropriate methods/properties to access fields where needed

note that the setter of the property only allows to increase the age by one as suggested in the answer you referenced. A property without logic would again be subject to the answer you referenced because it exposes the field without any control those breaking encapsulation again.