Auto-Implemented Properties for trivial Get (getter) and Set (setter) in C#

In the example given below, you will look at a very good example on auto-implemented properties for trivial get (getter) and set (setter).


There is a shortcut way to create property with its definition just by pressing keyboard keys.


Find here Tips: shortcut way to create properties in C#


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

namespace Automatically_Implemented_Properties
{
    class Program
    {
        static void Main(string[] args)
        {
            // Intialize a new object.
            Customer cust1 = new Customer(500.50, "Abhimanyu", 12);
            //Modify a property
            cust1.TotalPurchases += 0.50;
            Console.WriteLine("Total Purchase = " + cust1.TotalPurchases);
            Console.WriteLine("Name = " + cust1.Name);
            Console.WriteLine("Customer ID = " + cust1.CustomerID);
            Console.ReadKey();
        }
    }
 
    //Customer Class
    class Customer
    {
        // Auto-Impl Properties for trivial get and set
        public double TotalPurchases { get; set; }
        public string Name { get; set; }
        public int CustomerID { get; set; }
 
        // Constructor
        public Customer(double purchases, string name, int ID)
        {
            TotalPurchases = purchases;
            Name = name;
            CustomerID = ID;
        }
    }
}

There are couples of key points to note when using automatic properties. The first is that we don't define the bodies of the getter and setter. The second is that we don't define the field that the property is backed by. Both of these are done for us by the C# compiler when we build our class. Using an automatic property is no different from using a regular property as code given above. By using automatic properties, we save ourselves some typing, create code that is easier to read, and still preserve the flexibility that a property provides.

A Nice YouTube Post for the reference



Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples