• home
  • Email: trainings@synapseindia.careers

Blogs

back

Properties in C#

Jul 12, 2016

A property is a kind of class member which provides a way to read, write, or compute the value of a private field. The best thing about Properties are than it can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.


See the below examples:

class TimeChanger
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class myclass
{
    static void Main()
    {
        TimeChanger t = new TimeChanger();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 14;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}