0

I am new to C#. We declare Private member variable in a class to make them inaccessible from outside the class in which they are declared, but we can do this simply declaring them 'private' so what's the need of using set and get with them? for e.g i have a class customer

class Customer 
    {
        private double TotalPurchases; // { get; set; }
        private string Name; // { get; set; }
        private int CustomerID; // { get; set; }
        public Customer(double tp, string nam, int id) 
        {
            TotalPurchases = tp;
            Name = nam;
            CustomerID = id;
        }

        public void value() 
        {
            Console.WriteLine("Total purchases so far " + TotalPurchases + " " + Name + " " + CustomerID);
        }
    }

    class Program 
    {
        static void Main() 
        {
            // Intialize a new object.
            Customer cust1 = new Customer(20.0, "C#", 10);
            cust1.value();
            Console.ReadLine();
        }
    }

when i remove comment in customer class and allow properties to use set and get, it makes no difference at all!!!

Nino
  • 6,931
  • 2
  • 27
  • 42
ZigZag
  • 53
  • 6

1 Answers1

3

Without get; set; it behaves as Field and with Field there is no control over when and how the Field is assigned or retrieved.

If get set is present, you can control what value remains in Property based on some logic.

private string _foo;
public string Foo
{
    get
    {
        if (_foo == null) return string.Empty;
        return _foo;
    }
    set
    {
        if (value == null) return;
        _foo = value;
    }
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208