C# Properties

Updated on     Kisan Patel

In C#, a property is a member that provide flexible mechanism to read, write or compute the value of a private field.

Or

Properties are fields. A field member can be accessed directly, but a property member is always accessed through accessor and modifier methods called get and set, respectively.

The following syntax is used for writing a property :

public <type> <Property Name> {
        get {
           return <var>;
        }
        set {
           //validate the input, found in value
           if( IsValid(value))
              <var> = value;
        }
}

Let’s take one example how to working with properties in C# programming language.

using System;

namespace ConsoleApp
{
    class myClass
    {
        private bool _Gender;
        private int _Age;

        // Gender property.
        public bool Gender
        {
            get
            {
                return _Gender;
            }
            set
            {
                _Gender = value;
            }
        }
        // Age property
        public int Age
        {
            get
            {
                return _Age;
            }
            set
            {
                _Age = value;
            }
        }
    }

    class TestmyClass
    {
        static void Main()
        {
            myClass cls = new myClass();

            // set properties values
            cls.Gender = true;
            cls.Age = 25;
            if (cls.Gender)
            {
                Console.WriteLine("The Gender is Male");
                Console.WriteLine("Age is " + cls.Age.ToString());
            }
        }
    }
}

The output of the above c# program…

c-sharp-properties-demo

  • In above example, we have create two properties of myClass. Age and Gender.
  • Age is an integer property, and Gender is a Boolean type property.
  • As you can see, the get and set keywords are used to get and set property values.

Creating a Read-Only Property

A read-only property is a property that has a get() accessor but does not have a set() accessor.

This means that you can retrieve the value of a variable but you can not assign a value to the variable.

using System;

namespace ConsoleApp
{
    class PropertyHolder
    {
        private int _Age = 40;

        public int Age
        {
            get
            {
                return _Age;
            }
        }
    }

    class PropertyTester
    {
        public static void Main(string[] args)
        {
            PropertyHolder propHold = new PropertyHolder();
            Console.WriteLine("Your age is : " + propHold.Age);
        }
    }
}

The output of the above C# program…

c-sharp-read-only-properties-demo


C#

Leave a Reply