Saturday, 28 May 2016

auto property implementation

Auto implementation property was introduce in c# 3.0
It is introduce to make very simple use of implementation of properties in class.
Property is used to access private fields of class and also you can validate fields before initialize or set value.
Let’s take an example of private field of class with public property.

class Customer
{
    private int _id;

    public int Id
    {
        get {
            return _id;
        }
        set {
            _id = value;
        }
    }
}
There is lots of code write to get and set private fields using property. Now with auto property implementation we can just define getter and setter without implementation.

Syntax:

class Customer
{
    public int Id { get; set; }
}

Let's take a good example with a class.

using System;

class Program
{
    static void Main()
    {
        Customer cust = new Customer(){Id=1,Name = "Sample", Email = "sample@example.com", Mobile = "01234567980"};
        cust.print();
    }
}

class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }

    public void print()
    {
        Console.WriteLine("Id: {0}", this.Id);
        Console.WriteLine("Name: {0}", this.Name);
        Console.WriteLine("Email: {0}", this.Mobile);
        Console.WriteLine("Mobile: {0}", this.Email);
    }
}
Output:
Id: 1
Name: Sample
Email: 01234567980
Mobile: sample@example.com
Press any key to continue…

In the above example you can see that we have created customer class with public properties using auto implementation property and simple print method which prints information of new customer.
you can also visit:  www.mybook-lang.com

No comments:

Post a Comment