Automatic Properties in C#

Leave a Comment

Automatic properties use an abbreviated syntax for declaring properties e.g., instead of declaring a private data called customerID and the corresponding public property CustomerID as:
private int customerID;
public int CustomerID
{
get { return customerID; }
set { customerID = value; }
}

We can declare,
public int CustomerID { get;  set; }   // automatic property

The compiler will generate the same code as the full public property and the corresponding private data customerID. The limitation in an automatic property is that you cannot write your additional code in the get or the set part. The automatic properties become very handy when creating classes corresponding to database tables.

Solution
Suppose there is a table called Products in a database with the following design.


Create a Products class using automatic properties to map it to the above table.

Now, Create a Windows application in VS. Name the project NewOOFeatures. Add a class to the project called “Product.cs” with the following code.
namespace NewOOFeatures
{
    class Product
    {
        // automatic properties
        public int ProductId { get; set; }
        public int CatId { get; set; }
        public string ProductSDesc { get; set; }
        public string ProductLDesc { get; set; }
        public string ProductImage { get; set; }
        public decimal Price { get; set; }
        public bool InStock { get; set; }
        public int Inventory { get; set; }
    }
}

0 comments:

Post a Comment