Properties

Properties are the C# standard for accessing private data members inside a class. They may behave like normal fields, but properties have getters which gets the value of the private data and setters which sets a value to a private data. Getters and setters can directly retrieve and assign values to a private field or you can write custom code inside those to customize the behavior of retrieval and assignment to a field. Properties are typically public as they are usually consumed from the outside of the class. The example below shows how to define and use properties.

using System;
 
namespace PropertiesDemo
{
    public class Person
    {
        private string name;
        private int age;
        private double height;
 
        public string Name       
        {                        
            get                  
            {                    
                return name;     
            }                    
            set                  
            {                    
                name = value;    
            }                    
        }                        
 
        public int Age           
        {                        
            get                  
            {                    
                return age;      
            }                    
            set                  
            {                    
                age = value;     
            }                    
        }                        
 
        public double Height     
        {                        
            get                  
            {                    
                return height;   
            }                    
            set                  
            {                    
                height = value;  
            }                    
        }                        
 
        public Person(string name, int age, double height)
        {
            this.name = name;
            this.age = age;
            this.height = height;
        }
 
    }
 
    public class Program
    {
        public static void Main()
        {
            Person person1 = new Person("Jack", 21, 160);
            Person person2 = new Person("Mike", 23, 158);
 
            Console.WriteLine("Name: {0}", person1.Name);
            Console.WriteLine("Age: {0} years old", person1.Age);
            Console.WriteLine("Height: {0}cm", person1.Height);
 
            Console.WriteLine(); //Seperator                     
 
            Console.WriteLine("Name: {0}", person2.Name);
            Console.WriteLine("Age: {0} years old", person2.Age);
            Console.WriteLine("Height: {0}cm", person2.Height);
 
            person1.Name = "Frank"; 
            person1.Age = 19;       
            person1.Height = 162;   
 
            person2.Name = "Ronald";
            person2.Age = 25;       
            person2.Height = 174;   
 
            Console.WriteLine(); //Seperator                     
 
            Console.WriteLine("Name: {0}", person1.Name);
            Console.WriteLine("Age: {0} years old", person1.Age);
            Console.WriteLine("Height: {0}cm", person1.Height);
 
            Console.WriteLine();
 
            Console.WriteLine("Name: {0}", person2.Name);
            Console.WriteLine("Age: {0} years old", person2.Age);
            Console.WriteLine("Height: {0}cm", person2.Height);
        }
    }
}

Example 1 – Properties Demo

Name: Jack
Age: 21 years old
Height: 160cm

Name: Mike
Age: 23 years old
Height: 158cm

Name: Frank
Age: 19 years old
Height: 162cm

Name: Ronald
Age: 25 years old
Height: 174cm

The program introduces the use of properties and we defined three properties which correspond to each of the data members.

private string name;
private int age;
private double height;

These fields are also called backing fields of the properties. Notice that we made our data members private to promote encapsulation. Their values can only be accessed through the provided properties.

public string Name
{
    get
    {
        return name;
    }
    set
    {
        name = value;
    }
}

public int Age
{
    get
    {
        return age;
    }
    set
    {
        age = value;
    }
}

public double Height
{
    get
    {
        return height;
    }
    set
    {
        height = value;
    }
}

These are the properties. When writing a property, we indicate its accessibility which is public and we provide the data type which is the data type of the value it will return or accept. Notice that the name of the properties are the same as their corresponding data members except that the first letter is capitalized. It doesn’t have to, but that is another convention in C#. Inside the body, you see getters and setters. The getter, indicated by the get keyword, allows you to extract the data from a private data member. The setters, indicated by the set keyword allows you to set a value to a data member. Notice the value keyword inside the setter. The value contains what is being assigned to the property.

To access a property, you simply use the dot syntax.

Console.WriteLine("Name: {0}", person1.Name);
Console.WriteLine("Age: {0} years old", person1.Age);
Console.WriteLine("Height: {0}cm", person1.Height));

Calling a property this way will execute the code inside the body of the getter of the specified property. The getter then returns the value to the caller just like a method. Setting value to a property is also very simple.

person1.Name = "Frank";
person1.Age = 19;
person1.Height = 162;

The statements above calls the setter of each of those properties which assign the value to the corresponding data members.

Using properties is very flexible especially you want to add validation when getting or setting data to the members of the object. For example, you can add a restriction that only positive number can be assigned to the age of the person. You can modify the setter of the Age property like this:

public int Age           
{                        
    get                  
    {                    
        return age;      
    }                    
    set                  
    {                    
        if (value > 0) 
          age = value; 
        else           
          age = 0;     
    }                    
}

This time, if a user tries to assign a negative number to the age of the person, it will assign 0 instead because of the if statement inside the setter of the property.

You can also make a property read-only (cannot be set with values) by not including a setter. For example, you can make the Nameproperty read-only by doing the following:

public string Name
{
    get
    {
        return name;
    }
}

When you try to assign a new value to name, then an error will occur. Another thing is that you can also place access specifiers for getters and setters. Consider the following code:

public string Name
{
    get
    {
        return name;
    }
    private set
    {
        name = value;
    }
}

The Name property can only be read outside the class, but only methods inside the Person class can set new values.

A property doesn’t need to be associated to one private data member. It can be a combination of two data. Consider the code below.

private string firstName;
private string lastName;

public FullName
{
   get { return firstName + " " + lastName; }
}

We defined a read-only property called FullName which returns the combination of firstName and lastName separated by a space.

Automatic Properties


C# also offers a shortcut when creating properties. You can define a property without any private data member associated with it.

public int MyProperty { get; set; }

This feature is also called automatic properties which were introduced in C# 3.0. Notice that we didn’t supply any code for the getter and setter. The above statement is equivalent to defining a private int data member and it’s corresponding property except that the shorthand version is done in one line. This is automatically recognized by the compiler as a property and a corresponding backing field is created during runtime. Note that when defining automatic properties, you must have both the getter and the setter. You also cannot put codes inside the getter or setter of an automatic property.

Auto-Property Initializer


A new feature in C# 6 called auto-property initializers allows us to initialize values of automatic properties. The initial value will be assigned to the underlying backing field of the automatic property. You cannot use auto-property initializer on non-automatic properties (as the name implies). Here is an example of using auto-property initializer.

public class Person
{
    public string FirstName { get; set; } = "FirstName";

    public string LastName { get; set; } = "LastName";

    public DateTime DateOfBirth { get; set; } = new DateTime(1990, 1, 1);
}

To use auto-property initializer, just assign a default value right after the closing curly brace of the automatic property, and terminating it with a semicolon.

You can also use auto-property on a getter only or read-only property.

public string FullName { get; } = "John Smith";

Written by compitionpoint

Leave a Comment

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