C#

Learning Properties in C#

In this post on Learning Properties in C#, I will talk about an important member of a C# class called the Property. Usually, we have private fields in a class that we can manipulate using methods. However, many times we don’t need to do anything else with those private fields except setting and getting their values. In such a case, properties provide us a convenient way to do so without having the need to define the corresponding setter and getter methods for every field.

After all, Why Do We Need Properties, If We already have Fields?

To illustrate this point, let us have a class having certain data members. In the absence of properties, we maintain data encapsulation as follows. Evidently, class A has a private data member i that we access using the two public methods called getI() and setI().

class A
    {
        int i;
        public int getI()
        {
            return i;
        }
        public void setI(int i)
        {
            this.i = i;
        }
    }

Properties help us simplifying the way we access and manipulate a field. As an illustration look at the following code.

class A
    {
       int i;
       public int I
        {
            get
            {
                return i;
            }
            set
            {
                i = value;
            }
        }
    }

In the above code, class A has a property called I, which facilitates access to the private field i.

The syntax for Creating Properties in C#

We define properties in a class along with the corresponding field and the property itself doesn’t specify any storage. Basically, the field has allocated the storage for the value. However, it is not necessary to have any field for a property. In such a case, the property itself specifies the storage for a value.

Creating a Property for a Field

The following syntax shows how to create properties for a field.

class class-name
{
   data-type field-name;
   access-modifier data-type property-value
   {
       get{
             //Statements;
             return field-name;
          }
       set{
             //Statements;
             field-name=value;
          }
   }

}

Property Accessors

A property can have two types of accessors – the get accessor, and the set accessor.

get accessor

The get accessor provides a way to retrieve the value of the corresponding field. Hence, it must have a return statement.

set accessor

The set accessor enables us to set the value of the corresponding field.

It is important to remember that a property must have at least one accessor. however, it is not mandatory to define both accessors in a property.

Examples of Creating Properties

Meanwhile, here are some examples of creating properties in several ways. Firstly, we create a property of string type in the usual way as given below.

    class Animal
    {
        String name;
        public String Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
    }

Another example of using much-simplified syntax for accessors in a property is given below. Basically, we can create properties in this way if get and set accessors contain only one statement.

class Animal
    {
        String name;
        public String Name
        {
            get => name;
            set => name = value;
        }
    }

Using Access Modifiers with Properties

While using access modifiers with properties we need to remember following points:

  1. In particular, we can use any access modifier with properties.
  2. Also, we can use access modifiers with accessors.
  3. Further, we can use access modifiers with accessors only when the property has both get and set accessors.
  4. However, we can use an access modifier only with one of the accessors.
  5. Additionally, the access modifier used with an accessor must be more restrictive as compared to the access modifier used with the property itself. For instance, the following code will give an error because the get accessor is public.
class MyClass
    {
        int a;
        internal int A
        {
           public get => a;
           set => a = value;
        }
    }

Different Types of Properties

Learning Properties in C# requires understanding different types of properties. Meanwhile, we can have auto-implemented properties, read-write properties, read-only properties, write-only properties, and static properties.

Auto-implemented Properties

Significantly, we can have properties without any backing field. In fact, the C# compiler provides the backing field for an auto-implemented property. Besides, the accessors don’t contain any additional logic apart from assigning a value or retrieving a value.

The following syntax is used to create an auto-implemented property.

class class-name
{
   //Defining property
   public data-type property-name
   {
       get; set;
   }
}

In addition, we can initialize the auto-implemented property with a particular value also. The following example demonstrates the property initialization. It must be remembered that only auto-implemented properties can have initializers.

using System;
namespace PropertiesExamples
{
    class Box
    {
        public string Color { get; set; } = "Blue";
    }
    class Program
    {
        static void Main(string[] args)
        {
            Box ob = new Box();
            Box ob1 = new Box();
            ob.Color = "Red";
            Console.WriteLine(ob.Color+" "+ob1.Color);
        }
    }
}

Output

Red  Blue

Read-Write Properties

Specifically, if the property has both get and set accessors, then it is a read-write property as shown below.

class MyClass
    {
        int a;
        public int A
        {
           internal get => a;
           set => a = value;
        }
    }

Read-Only Properties

Likewise, we can have a read-only property if it allows only retrieving the value of the corresponding field using the get accessor. Accordingly, if we define only the get accessor in the property and omit the set accessor, then it becomes a read-only property.

Write-Only Properties

In a similar way, suppose we omit the get accessor and leave only the set accessor, then it is a write-only property. As an illustration, the following code demonstrates both read-only, and write-only properties. While A and B are write-only properties, the Sum is the read-only property.

using System;

namespace PropertiesExamples1
{
    class MyClass
    {
        int a, b;
        public int A
        {
           set => a=value;
        }
        public int B
        {
            set => b = value;
        }

        public int Sum
        {
            get => a+b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass ob = new MyClass();
            ob.A = 10;
            ob.B = 20
;
            Console.WriteLine("Sum = "+ob.Sum);
        }
    }
}

Output

Demonstration of Read-Only and Write-Only Properties
Demonstration of Read-Only and Write-Only Properties

Static Properties

In like manner, we can have static properties that have a single value for all instances of a class. Besides, we can access the static properties through the name of the class since creating an instance of the class is not necessary for accessing a static property. The following example shows a static property.

class MyClass
    {
        static int count;
        public static int Count
        {
            get => count;
            set => count = value;
        }
    }

Computed Properties

Finally, we can have properties that just not return the value of a field. Instead, it computes something and returns that computed value. The following code demonstrates a computed property.

using System;
namespace PropertiesExamples
{
    class Person
    {
        public int HouseNo { get; set;}
        public String Locality { get; set;}
        public String City { get; set;}
        public String PinCode { get; set;}
        public String Country { get; set;}
        public String Address { get => $@"{HouseNo}, {Locality},
{City} - {PinCode},
{Country}."; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person ob2 = new Person();
            ob2.HouseNo = 78;
            ob2.Locality = "Janakpuri";
            ob2.City = "Delhi";
            ob2.PinCode = "110078";
            ob2.Country="India";

            Console.WriteLine(ob2.Address);
        }
    }
}

Output

Learning Properties in C#
Learning Properties in C#

Benefits of Using Properties

  1. Basically, properties allow access and manipulation of private fields.
  2. They help us maintain the features of data hiding and encapsulation.
  3. Moreover, we can use properties for validating data and performing some computation on the basis of other fields.

Summary

In this article on Learning Properties in C#, I have explained a type member in C# called Property. Also, there are various ways to create properties, that are also discussed here. Further, we can have different types of properties like read-write properties, readonly properties, computed properties, auto-implemented properties, and static properties.


Related Topics

A Beginner’s Tutorial on WPF in C#

Everything about Tuples in C# and When to Use?

Linear Search and Binary Search in C#

Creating Jagged Arrays in C#

Learning Indexers in C#

Understanding Method Parameter Modifiers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Practice Questions

C# Basic Examples

Private and Static Constructors in C#

Constructors in C#

C# Arrays

C# Examples

How to Create a C# Console Application

Creating Navigation Window Application Using WPF in C#

LINQ To SQL Examples

Understanding the Concept of Nested Classes in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Examples of Extension Methods in C#

Learning All Class Members in C#

Leave a Reply

Your email address will not be published. Required fields are marked *