0

I am teaching myself C# and I was curious about the need for declaring private member variables that are accessed by public properties. The textbook I'm using says this is for the sake of encapsulation, but why do I need the private variables to begin with if the properties can be changed depending on their 'get' or 'set' functions? Here's an example:

namespace Practice
{
    struct Person
    {
        private int id;
        private string name;

        public int ID { get {return id;} set {id = value;} }
        public string Name { get; set; }
        public int Age { get; set; }
    }
    class Program
    { 
        static void Main(string[] args)
        {

            Person person = new Person();
            person.ID = 548;
            person.Name = "Dude";

            Console.WriteLine(person.Name);
        }
    }
}

So Name and ID operate the exact same way, so what's the purpose of declaring private int id and private string name?

Asif
  • 748
  • 3
  • 9
  • 32

1 Answers1

3

In your case, since you are not doing anything with the backing field (private field), you don't need it. You can work with auto properties (but, remember, auto properties use backing field in the background).

Having a backing field is useful if you are doing any operation with it, for example, if you want to verify that the ID should always be greater than 100, then you can do

public int ID
{
    get
    {
        return id;
    }
    set
    {
        if(id <= 100) throw new Exception("Invalid ID provided");
        id = value;
    }
}

If you try to apply the same logic on your property, instead of backing field, then you will/could run into infinite recursion.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • A backing variable would also be necessary if you wanted to have a default value for the variable other than the default value of the data type. – Russ Wilson Jul 14 '15 at 15:16