Skip to main content

Class Properties in C# Explained

Properties in C#

Property is an extension of class variable and it provides a mechanism to read, write or change the value of the class variable without affecting the external way of accessing it.

 

Properties can contain one or two code blocks called accessors and those are called a get accessor and set accessor in C#. By using get and set accessors, we can change the internal implementation of class variables and expose it without affecting the external way of accessing it.

 

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

 

The following is the syntax of defining a property with get and set accessor in C#.

 

 <access_modifier> <return_type> <property_name>

        {

            get

            {

                // return property value

            }

            set

            {

                // set a new value

            }

        }

If you observe the 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 the class variables.

 

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.

 

The properties are categorized as three types in C#, these are.

Type

Description

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 that contains only get accessor is called a read-only property.

Write Only

A property that contains only set accessor is called a read-only property.

 

Properties won’t accept any parameters and we should not pass a property as a ref or out parameter in C#.

 

The following is a simple example of defining a private variable and a property in C# language.

 

    public class Person

    {

        private string name;

        public string Name

        {

            get { return name; }

            set { name = value; }

        }

    }

 

If you observe the above sample code, 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 used only to return the field value or to compute it and return it but we should not use it for changing the state of an object.

 

As discussed earlier, we can extend the behavior of class variables using properties get and set accessors. The following code is an example of extending the behavior of private variable in property using get and set accessors in C#.

 

     public class Person

    {

        private string name = "Musa Sule";

        public string Name

        {

            get

            {

                return name.ToUpper();

            }

            set

            {

                if (value == "Gadabs")

                    name = value;

            }

        }

    }

 

From the above example, we are extending the behavior of private variable name using a property called Name with get and set accessors by performing some validations like to make sure Name value equals to only “Gadabs” using set accessor and converting property text to uppercase with get accessor.

 

Here the field “name” is marked as private so if you 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 a 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.

 

The below code is an example of invoking get and set accessors of properties in C#.

 

Person u = new Person();

 

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

 

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

 

Example of Get and Set in C# Properties

The following is an example of defining properties with get and set accessors to implement required validations without effecting the external way of using it in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        private string location;

        private string name = "Musa Sule";

        public string Location

        {

            get { return location; }

            set { location = value; }

        }

        public string Name

        {

            get

            {

                return name.ToUpper();

            }

            set

            {

                if (value == "Gadabs")

                    name = value;

            }

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Person person = new Person();

            // set accessor will invoke

            person.Name = "Sakinat";

            // set accessor will invoke

            person.Location = "Abuja";

            // get accessor will invoke

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

            // get accessor will invoke

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

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

            Console.ReadLine();

        }

    }

}

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

 

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


Propeerty


From the above output screen, our variable text converted to upper case and even after we set variable text as “Sakinat”, it displayed text as “Musa Sule” because of the set accessor validation fails in the property.

Creating Read-Only Properties

As earlier discussed, if a property contains the only get accessor, then its call a read-only property. The following is the example of creating read-only properties in C# language.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        private string _name;

        private string _location;

        public Person(string name, string location)

        {

            _name = name;

            _location = location;

        }

        public string Name

        {

            get

            {

                return _name;

            }

        }

        public string Location

        {

            get

            {

                return _location;

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Person person = new Person("Musa Sule", "Abuja");

            // compile error

            // u.Name = "Sakinat";

            // get accessor will invoke

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

            // get accessor will invoke

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

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

            Console.ReadLine();

        }

    }

}

 

If we observe the above sample code, 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 you execute the above program, you will get a result like as shown below.

 

Read_only Property

 

Creating Write Only Properties

As earlier discussed, if a property contains the only set accessor, then its call a write-only property. Following is the example of creating write-only properties in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        private string name;

        public string Name

        {

            set

            {

                name = value;

            }

        }

        private string location;

        public string Location

        {

            set

            {

                location = value;

            }

        }

        public void GetPersonDetails()

        {

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

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

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Person person = new Person();

            person.Name = "Musa Sule";

            person.Location = "Abuja";

            // compile error

            //Console.WriteLine(u.Name);

            person.GetPersonDetails();

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

            Console.ReadLine();

        }

    }

}

 

If you observe above sample code, 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 you execute the above program, you will get a result like as shown below.

 

Write_only Property
 

Auto Implemented Properties in C#

 

A property is called as an auto-implemented property when it contains accessors (getset) without having any logic implementation.

 

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

 

The following is an example of creating auto-implemented properties in C# language.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        public string Name { get; set; }

        public string Location { get; set; }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Person person = new Person();

            person.Name = "Musa Sule";

            person.Location = "Abuja";

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

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

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

            Console.ReadLine();

        }

    }

}

 

Auto Property
 

Thank you

 

References

1.     Tutlane

2.     c-sharpcorner

3.     w3schools

4.     microsoft

 


Comments

Popular posts from this blog

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...