C#: Get & set for auto-implemented properties

Sometimes, you might want to implement a minor or trivial logic change to a variable.  It can be done by using get and set accessors.  These are also called auto-implemented properties in C#.

Following the previous example, this example here will automatically capitalize the name variable.

Auto-Implemented Properties
using System;

namespace Automatic
{
    public class Employee
    {
        private string name;

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                name = value.Trim().ToUpper();
            }
        }
    }

    class Program
    {
        static void Main()
        {
            Employee e1 = new Employee();
            e1.Name = "John";  //This will set name to John
            Console.WriteLine(e1.Name);  //This will get the name
            Console.ReadLine();
        }
    }
}

The output from running above code will be JOHN.

Here is another example where a value of 50.55 is automatically added.
using System;

namespace Auto
{
    class Customer
    {
        // Auto-Impl Properties for trivial get and set 

        private double totalPurchases;

        public double TotalPurchases { 
            get 
                 {
                return totalPurchases; 
            } 
            set 
            { 
                totalPurchases = value + 50.55; 
            } 
        
        }
        // Constructor 
        public Customer(double purchases)
        {
            totalPurchases = purchases;
        }
    }

    class Program
    {
        static void Main()
        {
            // Intialize a new object.
            Customer cust1 = new Customer(0);

            //Modify a property
             cust1.TotalPurchases = 1012.32; //Setting the value

            Console.WriteLine(cust1.TotalPurchases);
            Console.ReadLine();
        }
    }
}

The output from running the above code will be 1062.87 instead of 1012.32.

Series Navigation<< C#: Using property to retrieve string length
C#: Constructor overloading >>