Property in C# : get set

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages this is often accomplished by programs implementing specialized getter and setter methods
  • 3279

Introduction

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field. Another benefit of properties over fields is that you can change their internal implementation over time. With a public field the underlying data type must always be the same because calling code depends on the field being the same. However, with a property you  can change the implementation. For example if a customer has an ID that is originally stored as an int you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code.

Example : Now, lets see how to use properties.

Code

using System;

public class Customer

{

    private int m_id = -1;

    public int ID

    {

        get

        {

            return m_id;

        }

        set

        {

            m_id = value;

        }

    }

    private string m_name = string.Empty;

    public string Name

    {

        get

        {

            return m_name;

        }

        set

        {

            m_name = value;

        }

    }

public class CustomerManagerWithProperties

{

    public static void Main()

    {

        Customer cust = new Customer();

        cust.ID = 1;

        cust.Name = "Amelio Rosales";

        Console.WriteLine(

          "ID: {0}, Name: {1}",

           cust.ID,

           cust.Name);

       Console.ReadKey();

    }

}
 

Summary : The Customer class has the ID and Name property implementations. There are also private fields named m_id and m_name; which ID and Name, respectively, encapsulate. Each property has two accessors, get and set. The get accessor returns the value of a field. The set accessor sets the value of a field with the contents of value, which is the value being assigned by calling code. The value shown in the accessor is a C# reserved word.

© 2018 DotNetHeaven. All rights reserved.