CSharp - Properties encapsulate an object state.

Introduction

A property is a member that can read, write, or compute the value of a private field.

Properties have either get or set or both blocks attached with them.

These blocks are called accessors.

get blocks are used for reading purposes and set blocks are used for assigning purposes.

In the following code, we have complete control of getting or setting a value of private members.

Demo

using System;

class MyClass//w  w  w .  j a  va 2s  . c  o m
{
    private int myInt; // also called private "backing" field
    public int MyInt   // The public property
    {
        get
        {
            return myInt;
        }
        set
        {
            myInt = value;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass ob = new MyClass();
        //ob.myInt = 10;//Error: myInt is inaccessible
        //Setting  a new value
        ob.MyInt = 10;//Ok.We'll get 10
                      //Reading the value
        Console.WriteLine("\nValue of myInt is now:{0}", ob.MyInt);
        //Setting another value to myInt through MyInt
        ob.MyInt = 100;
        Console.WriteLine("Now myInt value is:{0}", ob.MyInt);//100
    }
}

Result

The contextual keyword 'value' is an implicit parameter associated with properties. We typically use it for the assignment.

With properties, any of these modifiers can be used: public, private, internal, protected, new, virtual, abstract, override, sealed, static, unsafe, and extern.

Related Topic