Table of Contents
- Introduction
- Properties (the definition)
- Roadmap
- Properties (the explanation)
- Get accessor
- Set accessor
- 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
- Properties in Inheritance
- Summary
- Conclusion
IntroductionMy 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.”
RoadmapLet's recall our road map,
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
- namespace Properties
- {
- public class Properties
- {
- public string Name{}
- }
- }
Try to run/build the application, what do we get?
OutputError 'Properties.Properties.Name': property or indexer must have at least one accessorIn 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 2Let'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
- namespace Properties
- {
- public class Properties
- {
- public string Name
- {
- get
- {
- return "I am a Name property";
- }
- }
- }
- }
Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- Console.WriteLine(properties.Name);
- Console.ReadLine();
- }
- }
- }
Try to run/build the application. What do you get?
OutputIt 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 accessorNow 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
- using System;
-
- namespace Properties
- {
- public class Properties
- {
- public string Name
- {
- get
- {
- return "I am a Name property";
- }
- }
-
- public int Age
- {
- get
- {
- DateTime dateOfBirth=new DateTime(1984,01,20);
- DateTime currentDate = DateTime.Now;
- int age = currentDate.Year - dateOfBirth.Year;
- return age;
- }
- }
- }
- }
Call the “Age” property in the same way as done for Name.
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- Console.WriteLine(properties.Name);
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
Try to run/build the application, what do we get?
Output 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 1Properties.cs
- using System;
- namespace Properties
- {
- public class Properties
- {
- public string Name
- {
- get { return "I am a Name property"; }
- }
-
- public int Age
- {
- get
- {
- DateTime dateOfBirth = new DateTime(1984, 01, 20);
- DateTime currentDate = DateTime.Now;
- int age = currentDate.Year - dateOfBirth.Year;
- Console.WriteLine("Get Age called");
- return age;
- }
- set
- {
- Console.WriteLine("Set Age called " + value);
- }
- }
- }
- }
Call the “Age” property in the same way as done for Name.
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- Console.WriteLine(properties.Name);
- properties.Age = 40;
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
Run the application.
utputIn 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 2The 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
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name;
- private int age;
-
- public string Name
- {
- get { return name; }
- set
- {
- Console.WriteLine("Set Name called ");
- name = value;
- }
- }
-
- public int Age
- {
- get { return age; }
- set
- {
- Console.WriteLine("Set Age called ");
- age = value;
- }
- }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- properties.Name = "Akhil";
- Console.WriteLine(properties.Name);
- properties.Age = 40;
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
Run the application.
OutputNow 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 3Properties.cs
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name;
- private int age;
-
- public string Name { get; set; }
-
- public int Age { get; set; }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- properties.Name = "Akhil";
- Console.WriteLine(properties.Name);
- properties.Age = 40;
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
Run the application.
OutputThe 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.
ReadonlyA 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
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name="Akhil";
- private int age=32;
-
- public string Name
- {
- get { return name; }
- }
-
- public int Age { get { return age; } }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- properties.Name = "Akhil";
- Console.WriteLine(properties.Name);
- properties.Age = 40;
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
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 onlyIn the main method of the Program class, we tried to set the value of Age and Name property by:
- properties.Name = "Akhil";
- properties.Age = 40;
But since they aew readonly, in other words only have a get accessor, we encountered a compile time error.
Write-OnlyA 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
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name;
- private int age;
-
- public string Name
- {
- set { name=value; }
- }
-
- public int Age { set { age = value; } }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties properties=new Properties();
- properties.Name = "Akhil";
- Console.WriteLine(properties.Name);
- properties.Age = 40;
- Console.WriteLine("My age is " + properties.Age);
- Console.ReadLine();
- }
- }
- }
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 accessorIn the preceding example, our property is marked only with a set accessor, but we tried to access those properties in our main program with:
- Console.WriteLine(properties.Name);
- 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 1Can we define properties as two different set of pieces? The answer is
no.
Properties.cs
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name;
-
- public string Name
- {
- set { name=value; }
- }
-
- public string Name
- {
- get { return name; }
- }
- }
- }
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 2Can we define properties the same as a previously defined variable? The answer is
no.
Properties.cs
- using System;
- namespace Properties
- {
- public class Properties
- {
- private string name;
-
- public string name
- {
- set { name=value; }
- get { return name; }
- }
- }
- }
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 reference:
Differences Between Properties and Variables.Static PropertiesLike variables and methods, a property can also be marked static.
Properties.cs
- using System;
- namespace Properties
- {
- public class Properties
- {
- public static int Age
- {
- set
- {
- Console.WriteLine("In set static property; value is " + value);
- }
- get
- {
- Console.WriteLine("In get static property");
- return 10;
- }
- }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties.Age = 40;
- Console.WriteLine(Properties.Age);
- Console.ReadLine();
- }
- }
- }
OutputIn 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 typeLab 1Properties.cs
- using System;
-
- namespace Properties
- {
- public class Properties
- {
- public void AbsProperty
- {
- get
- {
- Console.WriteLine("Get called");
- }
- }
- }
- }
Compile the program.
The output is a compile time error.
Error 'AbsProperty': property or indexer cannot have void typePoint to remember
A property cannot have a void return type.
Lab 2
Just try to return a value from a “set” accessor.
Properties.cs
- using System;
-
- namespace Properties
- {
- public class Properties
- {
- public int Age
- {
- set { return 5; }
- }
- }
- }
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.
- using System;
-
- namespace Properties
- {
- public class Properties
- {
- public int Age
- {
- set { return ; }
- }
- }
- }
Value KeywordWe have a reserved keyword named value.
- using System;
-
- namespace Properties
- {
- public class Properties
- {
- public string Name
- {
- set { string value; }
- }
- }
- }
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 elseThis 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 PropertiesLab 1Yes, we can also have abstract properties. Let's see how it works.
Properties.cs
- using System;
-
- namespace Properties
- {
- public abstract class BaseClass
- {
- public abstract int AbsProperty { get; set; }
- }
-
- public class Properties : BaseClass
- {
- public override int AbsProperty
- {
- get
- {
- Console.WriteLine("Get called");
- return 10;
- }
- set { Console.WriteLine("set called,value is " + value); }
- }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties prop=new Properties();
- prop.AbsProperty = 40;
- Console.WriteLine(prop.AbsProperty);
- Console.ReadLine();
- }
- }
- }
OutputIn 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 2Properties.cs
- using System;
-
- namespace Properties
- {
- public abstract class BaseClass
- {
- public abstract int AbsProperty { get; }
- }
-
- public class Properties : BaseClass
- {
- public override int AbsProperty
- {
- get
- {
- Console.WriteLine("Get called");
- return 10;
- }
- set { Console.WriteLine("set called,value is " + value); }
- }
- }
- }
Program.cs
- using System;
-
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- Properties prop=new Properties();
- prop.AbsProperty = 40;
- Console.WriteLine(prop.AbsProperty);
- Console.ReadLine();
- }
- }
- }
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 InheritanceJust follow the code.
Properties.cs
- using System;
-
- namespace Properties
- {
- public class PropertiesBaseClass
- {
- public int Age
- {
- set {}
- }
- }
-
- public class PropertiesDerivedClass:PropertiesBaseClass
- {
- public int Age
- {
- get { return 32; }
- }
- }
- }
Program.cs
- namespace Properties
- {
- class Program
- {
- static void Main(string[] args)
- {
- PropertiesBaseClass pBaseClass=new PropertiesBaseClass();
- pBaseClass.Age = 10;
- PropertiesDerivedClass pDerivedClass=new PropertiesDerivedClass();
- ((PropertiesBaseClass) pDerivedClass).Age = 15;
- pDerivedClass.Age = 10;
- }
- }
- }
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 onlyIn 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.
SummaryLet's recall all the points that we need to remember.
- 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#.
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 !