Diving Into OOP (Day 7) - Properties in C# (A Practical Approach)

Table of Contents

  • Introduction
  • Properties (the definition)
  • Roadmap
  • Properties (the explanation)
    • Lab1
    • Lab2
  • Get accessor
    • Point to remember
  • Set accessor
    • Lab1
    • Lab2
      • Point to remember
    • Lab3
  • Readonly
  • Write-Only
  • Insight of Properties in C#
    • Lab1
    • Lab2
    • Properties vs Variables
  • Static Properties
  • Properties return type
    • Lab1
      Point to remember
    • Lab2
  • Value Keyword
  • Abstract Properties
    • Lab1
      • Point to remember
    • Lab2
      • Point to remember
  • Properties in Inheritance
  • Summary
  • Conclusion
Introduction

My article of the series “Diving into OOP” will explain properties, their uses and indexers in C#. We'll follow the same way of learning with less theory and more practice. I'll try to explain the concept in-depth.

Properties (the definition)

Let's start with the definition taken from the MSDN.

“A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.”

Roadmap

Let's recall our road map,

Roadmap

Properties (the explanation)

As a C# programmer, I must say that properties are something a C# programmer is blessed to use in his code. If we analyze the internals of properties, they are very different from normal variables. Internally, properties are methods that do not have their own memory like variables have. We can leverage a property to write our custom code whenever we access a property. We can access the code when we call/execute properties or during of declaration too, but this is not possible with variables. A property in easy language is a class member and is encapsulated and abstracted from the end developer who is accessing the property. A property can contain lots of code that an end user does not know. An end user only cares to use that property like a variable.

Let's start with some coding now.

Note: Each and every code snippet in this article is tried and tested.

Lab 1

Create a simple console application and name it “Properties”. Add a class named “Properties” to it. You can choose the names of the projects and classes depending on your wishes. Now try to create a property in that class as shown below.

Properties.cs

  1. namespace Properties  
  2. {  
  3.     public class Properties  
  4.     {  
  5.         public string Name{}  
  6.     }  
  7. }  
Try to run/build the application, what do we get?

Output

Error 'Properties.Properties.Name': property or indexer must have at least one accessor

In the preceding example, we created a property named Name of type string. The error we got is very self-explanatory; it says a property must have an accessor, in other words a get or a set. This means we need something in our property that gets accessed, whether to set the property value or get the property value. Unlike variables, properties cannot be declared without an accessor.

Lab 2

Let's assign a get accessor to our property and try to access that property in the Main method of the Program.cs file.

Properties.cs
  1. namespace Properties  
  2. {  
  3.     public class Properties  
  4.     {  
  5.         public string Name  
  6.         {  
  7.             get  
  8.             {  
  9.                  return "I am a Name property";  
  10.             }  
  11.         }  
  12.     }  
  13. }  
Program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace Properties  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Properties properties=new Properties();  
  13.             Console.WriteLine(properties.Name);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
Try to run/build the application. What do you get?

Output

application

It says “I am a Name property”. This signifies that our get successor got called when I tried to access the property or tried to fetch the value of a Property.

Get accessor

Now declare one more property in the Properties class and name it Age that returns an integer. It calculates the age of a person by calculating the difference between his date of birth and current date.

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     public class Properties  
  6.     {  
  7.         public string Name  
  8.         {  
  9.             get  
  10.             {  
  11.                  return "I am a Name property";  
  12.             }  
  13.         }  
  14.   
  15.         public int Age  
  16.         {  
  17.             get  
  18.             {  
  19.                 DateTime dateOfBirth=new DateTime(1984,01,20);  
  20.                 DateTime currentDate = DateTime.Now;  
  21.                 int age = currentDate.Year - dateOfBirth.Year;  
  22.                 return age;  
  23.             }  
  24.         }  
  25.     }  
  26. }  
Call the “Age” property in the same way as done for Name.

Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             Console.WriteLine(properties.Name);  
  11.             Console.WriteLine("My age is " + properties.Age);  
  12.             Console.ReadLine();  
  13.         }  
  14.     }  
  15. }  
Try to run/build the application, what do we get?

Output

build

It returns the correct age subjective to the date of birth provided. Did you notince something here? Our property contains some code and logic to calculate age, but the caller, Program.cs, is not aware of the logic. It only cares about using that Property. Therefore we see that a property encapsulates and abstracts its functionality from the end user, in our case it's a developer.

Point to remember

The Get accessor is only used to read a property value. A property having only “get” cannot be set with any value from the caller.

This means a caller/end user can only access that property in read mode.

Set accessor

Let's start with a simple example.

Lab 1

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         public string Name  
  7.         {  
  8.             get { return "I am a Name property"; }  
  9.         }  
  10.   
  11.         public int Age  
  12.         {  
  13.             get  
  14.             {  
  15.                 DateTime dateOfBirth = new DateTime(1984, 01, 20);  
  16.                 DateTime currentDate = DateTime.Now;  
  17.                 int age = currentDate.Year - dateOfBirth.Year;  
  18.                 Console.WriteLine("Get Age called");  
  19.                 return age;  
  20.             }  
  21.             set  
  22.             {  
  23.                 Console.WriteLine("Set Age called " + value);  
  24.             }  
  25.         }  
  26.     }  
  27. }  
Call the “Age” property in the same way as done for Name.

Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             Console.WriteLine(properties.Name);  
  11.             properties.Age = 40;  
  12.             Console.WriteLine("My age is " + properties.Age);  
  13.             Console.ReadLine();  
  14.         }  
  15.     }  
  16. }  
Run the application.

utput

Run

In the preceding example, I made a w minor changes in the get accessor, in other words just printing that control is in the “Get accessor” and introduced a “Set” in the Age property too. Everything else remains the same. Now when I call the Name property, it works as it worked earlier. Since we used “Set” we are now allowed to set the value of a property. When I do properties.Age = 40; that means I am setting the value 40 for that property. We can say a property can also be used to assign some value. In this case the Set accessor is called, as soon as we set a value to property. Later on when we access that same property, again our get accessor is called that returns the value with some custom logic. We have a drawback here. As we see, whenever we call get we get the same value and not the value that we assigned to that property, in other words because get has its custom fixed logic. Let's try to overcome this situation.

Lab 2

The example I am about to explain makes use of a private variable. But you can also use Automatic Properties to do it. I'll intentionally use a variable to clarify things.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name;  
  7.         private int age;  
  8.   
  9.         public string Name  
  10.         {  
  11.             get { return name; }  
  12.             set  
  13.             {  
  14.                 Console.WriteLine("Set Name called ");  
  15.                 name = value;  
  16.             }  
  17.         }  
  18.   
  19.         public int Age  
  20.         {  
  21.             get { return age; }  
  22.             set  
  23.             {  
  24.                 Console.WriteLine("Set Age called ");  
  25.                 age = value;  
  26.             }  
  27.         }  
  28.     }  
  29. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             properties.Name = "Akhil";  
  11.             Console.WriteLine(properties.Name);  
  12.             properties.Age = 40;  
  13.             Console.WriteLine("My age is " + properties.Age);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
Run the application.

Output

Properties

Now you see, we get the same value that we assigned to the Name and Age properties. When we access these properties the get accessor is called and it returns the same value as we set them to. Here the properties internally use a local variable to hold and sustain the value.

In daily programming, we normally create a Public property that can be accessed outside the class. However the variable it is using internally could be private.

Point to remember

The variable used for a property should be of the same data type as the data type of the property.

In our case we used the variables name and age, they share the same datatype as their respective properties do. We don't use variables since there might be scenarios in which we do not have control over those variables, the end user can change them at any point of code without maintaining the change stack. Moreover one major use of properties is for the user to associate some logic or action when some change on the variable occurs, therefore when we use properties, we can easily track the value changes in the variable.

When using Automatic Properties, they do this internally, in other words we don't need to define an extra variable to do so, as shown below.

Lab 3

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name;  
  7.         private int age;  
  8.   
  9.         public string Name { getset; }  
  10.   
  11.         public int Age { getset; }  
  12.     }  
  13. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             properties.Name = "Akhil";  
  11.             Console.WriteLine(properties.Name);  
  12.             properties.Age = 40;  
  13.             Console.WriteLine("My age is " + properties.Age);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
Run the application.

Output

Run the application

The following are automatic properties:

public string Name { get; set; }
public int Age { get; set; }


I hope now you understand how to define a property and use it.

Readonly

A property can be made read-only by only providing the get accessor. We do not provide a set accessor, if we do not want our property to be initialized or to be set from outside the scope of the class.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name="Akhil";  
  7.         private int age=32;  
  8.   
  9.         public string Name  
  10.         {  
  11.             get { return name; }  
  12.         }  
  13.   
  14.         public int Age { get { return age; } }  
  15.     }  
  16. }  
Program.cs 
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             properties.Name = "Akhil";  
  11.             Console.WriteLine(properties.Name);  
  12.             properties.Age = 40;  
  13.             Console.WriteLine("My age is " + properties.Age);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
Build the application, we get the following output.

Error Property or indexer 'Properties.Properties.Age' cannot be assigned to -- it is read only
Error Property or indexer 'Properties.Properties.Name' cannot be assigned to -- it is read only


In the main method of the Program class, we tried to set the value of Age and Name property by:
  1. properties.Name = "Akhil";  
  2. properties.Age = 40;  
But since they aew readonly, in other words only have a get accessor, we encountered a compile time error.

Write-Only

A property can also be made write-only, in other words the reverse of read-only. In this case you'll be only allowed to set the value of the property but can't access it because we don't have a get accessor in it.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name;  
  7.         private int age;  
  8.   
  9.         public string Name  
  10.         {  
  11.             set { name=value; }  
  12.         }  
  13.   
  14.         public int Age { set { age = value; } }  
  15.     }  
  16. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties properties=new Properties();  
  10.             properties.Name = "Akhil";  
  11.             Console.WriteLine(properties.Name);  
  12.             properties.Age = 40;  
  13.             Console.WriteLine("My age is " + properties.Age);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
Build the application, we get the following output:

Error The property or indexer 'Properties.Properties.Age' cannot be used in this context because it lacks the get accessor
Error The property or indexer 'Properties.Properties.Name' cannot be used in this context because it lacks the get accessor


In the preceding example, our property is marked only with a set accessor, but we tried to access those properties in our main program with:
  1. Console.WriteLine(properties.Name);  
  2. Console.WriteLine("My age is " + properties.Age);  
That means we tried to call the get accessor of the property that is not defined, so we again ended up in a compile-time error.

Insight of Properties in C#

Lab 1

Can we define properties as two different set of pieces? The answer is no.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name;  
  7.   
  8.         public string Name  
  9.         {  
  10.             set { name=value; }  
  11.         }  
  12.   
  13.         public string Name  
  14.         {  
  15.             get { return name; }  
  16.         }  
  17.     }  
  18. }  
Build the project, we get the following compile time error:

Error The type 'Properties.Properties' already contains a definition for 'Name'

Here I tried to create a single property segregated into two accessors. The compiler treats a property name as a single separate property, so we cannot define a property with two names having a different accessor.

Lab 2

Can we define properties the same as a previously defined variable? The answer is no.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         private string name;  
  7.   
  8.         public string name  
  9.         {  
  10.             set { name=value; }  
  11.             get { return name; }  
  12.         }  
  13.     }  
  14. }  
Build the project; we get the following compile time error:

Error The type 'Properties.Properties' already contains a definition for ‘name"

Again, we cannot have a variable and a property with the same name. They may differ on the grounds of case sensitivity, but they cannot share a common name with the same case because when they are accessed the compiler might be confused about whether you are trying to access a property or a variable.

Properties vs Variables

It is a misconception that variables are faster in execution than properties. I do not deny that but this may not be true in every case or can vary case to case. A property, as I explained, internally executes a function/method whereas a variable uses/initializes memory when used. At times properties are not slower than variables since the property code is internally rewritten to memory access.

To summarize, MSDN explains this theory better than me.

table

Table reference: Differences Between Properties and Variables.

Static Properties

Like variables and methods, a property can also be marked static.

Properties.cs
  1. using System;  
  2. namespace Properties  
  3. {  
  4.     public class Properties  
  5.     {  
  6.         public static int Age  
  7.         {  
  8.             set  
  9.             {  
  10.                 Console.WriteLine("In set static property; value is " + value);  
  11.             }  
  12.             get  
  13.             {  
  14.                 Console.WriteLine("In get static property");  
  15.                 return 10;  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties.Age = 40;  
  10.             Console.WriteLine(Properties.Age);   
  11.             Console.ReadLine();  
  12.         }  
  13.     }  
  14. }  
Output

Static Properties

In the preceding example, I created a static Age property. When I tried to access it, you can see it is accessed via class name, like all static members are subjected to. So properties also inherit the static functionality like all C# members, no matter whether it is variable or a method. They'll be accessed via class name only.

Properties return type

Lab 1

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.   public class Properties   
  6.     {  
  7.         public void AbsProperty  
  8.         {  
  9.             get  
  10.             {  
  11.                 Console.WriteLine("Get called");  
  12.             }  
  13.         }  
  14.     }  
  15. }  
Compile the program.

The output is a compile time error.

Error 'AbsProperty': property or indexer cannot have void type

Point to remember

A property cannot have a void return type.

Lab 2

Just try to return a value from a “set” accessor.

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.   public class Properties   
  6.     {  
  7.         public int Age  
  8.         {  
  9.             set { return 5; }  
  10.         }  
  11.     }  
  12. }  
Compile the program.

Error Since 'Properties.Properties.Age.set' returns void, a return keyword must not be followed by an object expression

Here the compiler understands the “set” accessor as a method that returns void and takes a parameter to initialize the value. So set cannot be expected to return a value.

If we just leave a return statement empty and remove 5, we do not get any error and the code compiles.
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.   public class Properties   
  6.     {  
  7.         public int Age  
  8.         {  
  9.             set { return ; }  
  10.         }  
  11.     }  
  12. }  
Value Keyword

We have a reserved keyword named value.
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.   public class Properties   
  6.     {  
  7.         public string Name  
  8.         {  
  9.             set { string value; }  
  10.         }  
  11.     }  
  12. }  
Just compile the preceding code, we get a compile time error as follows.

Error A local variable named 'value' cannot be declared in this scope because it would give a different meaning to 'value', that is already used in a 'parent or current' scope to denote something else

This signifies that “value” is a reserved keyword here. So one cannot declare a variable named value in the “set” accessor since it may give a different meaning to an already reserved keyword value.

Abstract Properties

Lab 1

Yes, we can also have abstract properties. Let's see how it works.

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     public abstract class BaseClass  
  6.     {  
  7.         public abstract int AbsProperty { getset; }  
  8.     }  
  9.   
  10.     public class Properties : BaseClass  
  11.     {  
  12.         public override int AbsProperty  
  13.         {  
  14.             get  
  15.             {  
  16.                 Console.WriteLine("Get called");  
  17.                 return 10;  
  18.             }  
  19.             set { Console.WriteLine("set called,value is " + value); }  
  20.         }  
  21.     }  
  22. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties prop=new Properties();  
  10.             prop.AbsProperty = 40;  
  11.             Console.WriteLine(prop.AbsProperty);   
  12.             Console.ReadLine();  
  13.         }  
  14.     }  
  15. }  
Output

Output

In the preceding example, I just created a base class named “BaseClass” and defined an abstract property named Absproperty. Since the property is abstract it follows the rules of being abstract as well. I inherited my “Properties” class from BaseClass and given the body to that abstract property. Since the property was abstract I need to override it in my derived class to add functionality to it. So I used the override keyword in my derived class.

In the base class, the abstract property has no body at all, neither for “get” nor for “set”, so we need to implement both of the accessors in our derived class, as shown in the “Properties” class.

Point to remember

If one does not mark a property defined in a derived class as override, it will by default be considered to be new.

For a better understanding see the Diving into OOP (Day 3) : Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism) article on new and override.

Lab 2

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     public abstract class BaseClass  
  6.     {  
  7.         public abstract int AbsProperty { get; }  
  8.     }  
  9.   
  10.     public class Properties : BaseClass  
  11.     {  
  12.         public override int AbsProperty  
  13.         {  
  14.             get  
  15.             {  
  16.                 Console.WriteLine("Get called");  
  17.                 return 10;  
  18.             }  
  19.             set { Console.WriteLine("set called,value is " + value); }  
  20.         }  
  21.     }  
  22. }  
Program.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Properties prop=new Properties();  
  10.             prop.AbsProperty = 40;  
  11.             Console.WriteLine(prop.AbsProperty);   
  12.             Console.ReadLine();  
  13.         }  
  14.     }  
  15. }  
Output

Compile time error.

Error 'Properties.Properties.AbsProperty.set': cannot override because 'Properties.BaseClass.AbsProperty' does not have an overridable set accessor

In the preceding lab example, I just removed “set” from the AbsProperty in the Base class. All the code remains the same. Now here we are trying to override the set accessor too in the derived class that is missing in the base class, therefore the compiler will not allow you to override a successor that is not declared in the base class, hence the result is a compile time error.

Point to remember

You cannot override an accessor that is not defined in a base class abstract property.

Properties in Inheritance

Just follow the code.

Properties.cs
  1. using System;  
  2.   
  3. namespace Properties  
  4. {  
  5.   public class PropertiesBaseClass   
  6.     {  
  7.         public int Age  
  8.         {  
  9.             set {}  
  10.         }  
  11.     }  
  12.   
  13.     public class PropertiesDerivedClass:PropertiesBaseClass  
  14.     {  
  15.         public int Age  
  16.         {  
  17.             get { return 32; }  
  18.         }  
  19.     }  
  20. }  
Program.cs
  1. namespace Properties  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             PropertiesBaseClass pBaseClass=new PropertiesBaseClass();  
  8.             pBaseClass.Age = 10;  
  9.             PropertiesDerivedClass pDerivedClass=new PropertiesDerivedClass();  
  10.             ((PropertiesBaseClass) pDerivedClass).Age = 15;  
  11.             pDerivedClass.Age = 10;  
  12.         }  
  13.     }  
  14. }  
As you can see in the preceding code, in the Properties.cs file I created two classes. One is Base, in other words PropertiesBaseClass and the second is Derived, in other words PropertiesDerivedClass. I intentionally declared a set accessor in the Base class and a get in the Derived class for the same property name, Age. Now this case may give you the feeling that when compiled, our code of property Age will become one, in other words it will take the set from the Base class and the get from the derived class and combine them into a single entity of Age property. But actually that is not the case. The compiler treats these properties differently and does not consider them to be the same. In this case the property in the derived class actually hides the property in the base class, they are not the same but independent properties.The same concept of method hiding applies here too. You can read about hiding in Diving into OOP (Day 3) : Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism).

To use the property of the base class from a derived class object, you need to cast it to the base class and then use it.

When you compile the preceding code, you get a compile time error as follows.

Error Property or indexer 'Properties.PropertiesDerivedClass.Age' cannot be assigned to -- it is read only

In other words we can do ((PropertiesBaseClass) pDerivedClass).Age = 15;

But we cannot do pDerivedClass.Age = 10; because the derived class property has no “set” accessor.

Summary

Let's recall all the points that we need to remember.

right

 

  • The variable used for a property should be the same data type as the data type of the property.
  • A property cannot have a void return type.
  • If one does not mark a property defined in the derived class as override, it will by default be considered as new.
  • You cannot override an accessor that is not defined in a base class abstract property.
  • A get accessor is only used to read a property value. A property having only a get cannot be set with any value from the caller.

Conclusion

In this article we learned a lot about properties in C#. I hope you now understand properties well. In my next article I'll explain all about indexers in C#.

smile

Keep coding and enjoy reading.

Also do not forget to rate/comment/like my article if it helped you by any means, this motivates and encourages me to write more and more.

Read more:

For more technical articles you can reach out to CodeTeddy

My other series of articles:

Happy coding !