C# Properties (GET, SET)

  Keywords : c# property, c# property get set, c# property example, c# interface property, c# readonly property, c# property default value, c# get set property name

Here we will learn what is property (get, set) in c#, how to create readonly property in c#, auto-implemented property in c#, write-only property in c#, static property in c# and how to use c# properties to get or set values with examples.

C# Properties

In c#, a Property is an extension of class variable and it provides a mechanism to read, write or change the value of class variable without effecting the external way of accessing it in our applications.

 

In c#, the properties can contain one or two code blocks called accessors, those are a get accessor and set accessor. By using get and set accessors, we can change the internal implementation of class variables and expose it without effecting the external way of accessing it based on our requirements.

 

Generally, in object oriented programming languages like c# we need to define a fields as private, and then use properties to access their values in public way with get and set accessors.

 

Following is the syntax of defining a property with get and set accessor in c# programming language.

 

<access_modifier> <return_type> <property_name>

{

    get

    {

        // return property value

    }

    set

    {

        // set a new value

    }

}

If you observe above syntax, we used an access modifier and return type to define a property along with get and set accessors to make required modifications to class variables based on our requirements.

 

Here, the get accessor code block will be executed whenever the property is read and the code block of set accessor will be executed whenever the property is assigned to a new value.

 

In c#, the properties are categorized as three types, those are.

 

TypeDescription
Read-Write A property which contains a both get and set accessors, then we will call it as read-write property.
Read-Only A property which contains only get accessor, then we will call it as read-only property.
Write-Only A property which contains only set accessor, then we will call it as write-only property.

In c#, Properties won’t accept any parameters and we should not pass property as a ref or out parameter in our application.

 

Following is the simple example of defining a private variable and a property in c# programming language.

 

class User

{

    private string name;

    public string Name

    {

        get { return name; }

        set { name = value; }

    }

}

If you observe above example, we defined a property called “Name” and we used a get accessor to return a property value and set accessors to set a new value. Here, the value keyword in set accessor is used to define a value that is being assigned by set accessor.

 

In c#, the get accessor needs to be use only to return the field value or to compute it and return it but we should not use it for changing the state of object.

 

As discussed, we can extend the behaviour of class variables using properties get and set accessors. Following is the example of extending the behaviour of private variable in property using get and set accessors in c# programming language.

 

class User

{

    private string name = "Suresh Dasari";

    public string Name

    {

        get

        {

            return name.ToUpper();

        }

        set

        {

            if (value == "Suresh")

                name = value;

        }

    }

}

If you observe above example, we are extending the behaviour of private variable name using property called Name with get and set accessors by performing some validations like to make sure Name value is equals to only “Suresh” using set accessor and converting property text to uppercase with get accessor.

 

Here the field “name” is marked as private so if want to make any changes to this field then we can do it only by calling the property (Name).

 

In c# properties, the get accessor will be invoked while reading the value of property and when we assign a new value to the property, then the set accessor will be invoked by using an argument that provides the new value.

 

Following is the example of invoking get and set accessors of properties in c# programming language.

 

User u = new User();

u.Name = "Rohini"; // set accessor will invoke

Console.WriteLine(u.Name); // get accessor will invoke

In above example, when we assign a new value to the property, then the set accessor will be invoked and the get accessor will invoked when we try to the read the value from property.

C# Properties Overview

Following are the important features of properties in c# programming language.

 

  • In c#, properties will enable class variables to expose in public way using get and set accessors by hiding implementation details.
  • In properties, a get accessor is used to return a property value and a set accessor is used to assign a new value.
  • The value  keyword in set accessor is used to define a value which is going to be assigned by the set accessor.
  • In c#, the properties are categorized as read-write, read-only or write-only.

C# Properties (Get, Set) Example

Following is the example of defining a properties with get and set accessors to implement required validations without effecting the external way of using it in c# programming language.

 

using System;

 

namespace Tutlane

{

    class User

    {

        private string location;

        private string name = "Suresh Dasari";

        public string Location

        {

            get { return location; }

            set { location = value; }

        }

        public string Name

        {

            get

            {

                return name.ToUpper();

            }

            set

            {

                if (value == "Suresh")

                    name = value;

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            User u = new User();

            // set accessor will invoke

            u.Name = "Rohini";

            // set accessor will invoke

            u.Location = "Hyderabad";

            // get accessor will invoke

            Console.WriteLine("Name: " + u.Name);

            // get accessor will invoke

            Console.WriteLine("Location: " + u.Location);

            Console.WriteLine("\nPress Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we are extending the behaviour of private variables (name, location) using properties (Name, Location) with get and set accessors by performing some validations like to make sure Name value is equals to only “Suresh” using set accessor and converting property text to uppercase with get accessor.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Properties (Get, Set) Example Result

 

If you observe above example, our variable text converted to upper case and even after we set variable text as “Rohini”, it displayed text as “Suresh Dasari” because the set accessor validation fails in property.

C# Create Read Only Properties

As discussed, if property contains only get accessor, then we will call it as read-only property. Following is the example of creating a read-only properties in c# programming language.

 

using System;

 

namespace Tutlane

{

    class User

    {

        private string name;

        private string location;

        public User(string a, string b)

        {

            name = a;

            location = b;

        }

        public string Name

        {

            get

            {

                return name;

            }

        }

        public string Location

        {

            get

            {

                return location;

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            User u = new User("Suresh Dasari", "Hyderabad");

            // compile error

            // u.Name = "Rohini";

            // get accessor will invoke

            Console.WriteLine("Name: " + u.Name);

            // get accessor will invoke

            Console.WriteLine("Location: " + u.Location);

            Console.WriteLine("\nPress Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a properties using only get accessor to make the properties are read-only based on our requirements.

 

In case, if we uncomment the commented code then we will get a compile error because our Name property doesn’t contain any set accessor to set a new value. It’s a just read-only property.

 

When we execute above c# program, we will get a result like as shown below.

 

C# Create Readonly Properties Example Result

 

This is how we can create read-only properties in c# applications based on our requirements.

C# Create Write Only Properties

As discussed, if property contains only set accessor, then we will call it as write-only property. Following is the example of creating a write-only properties in c# programming language.

 

using System;

 

namespace Tutlane

{

    class User

    {

        private string name;

        public string Name

        {

            set

            {

                name = value;

            }

        }

        private string location;

        public string Location

        {

            set

            {

                location = value;

            }

        }

        public void GetUserDetails()

        {

            Console.WriteLine("Name: " + name);

            Console.WriteLine("Location: " + location);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            User u = new User();

            u.Name = "Suresh Dasari";

            u.Location = "Hyderabad";

            // compile error

            //Console.WriteLine(u.Name);

            u.GetUserDetails();

            Console.WriteLine("\nPress Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a properties using only set accessor to make the properties are write-only based on our requirements.

 

In case, if we uncomment the commented code then we will get a compile error because our Name property doesn’t contain any get accessor to return a value. It’s a just write-only property.

 

When we execute above c# program, we will get a result like as shown below.

 

 

C# Create WriteOnly Properties Example Result

 

This is how we can create write-only properties in c# applications based on our requirements.

C# Auto Implemented Properties

In c#, a property is called as an auto-implemented property when it contains an accessors (get, set) without having any logic implementation.

 

Generally, the auto-implemented properties are useful whenever there is no logic implementation required in property accessors.

 

Following is the example of creating an auto-implemented properties in c# programming language.

 

using System;

 

namespace Tutlane

{

    class User

    {

        public string Name { get; set; }

        public string Location { get; set; }

    }

    class Program

    {

        static void Main(string[] args)

        {

            User u = new User();

            u.Name = "Suresh Dasari";

            u.Location = "Hyderabad";

            Console.WriteLine("Name: " + u.Name);

            Console.WriteLine("Location: " + u.Location);

            Console.WriteLine("\nPress Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a properties with get and set accessors without having any logic implementation.

 

When we execute above c# program, we will get a result like as shown below.

 

C# AutoImplemented Properties Example Result

 

This is how we can create auto-implemented properties in c# applications based on our requirements.