In Focus

Understanding Properties In C#

A property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. This article explains use and implementation of properties is classes in C# and .NET. You'll also learn about static properties and abstract properties.

A property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, properties are special methods called accessors. A property have two accessors, get property accessor and set property accessor. A get accessor returns a property value, and a set accessor assigns a new value. The value keyword represents the value of a property.

Properties in C# and .NET have various access levels that is defined by an access modifier. Properties can be read-write, read-only, or write-only. The read-write property implements both, a get and a set accessor. A write-only property implements a set accessor, but no get accessor. A read-only property implements a get accessor, but no set accessor.

C# Properties
 
In C#, properties are nothing but a natural extension of data fields. They are usually known as 'smart fields' in C# community. We know that data encapsulation and hiding are the two fundamental characteristics of any object oriented programming language. In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members. 

Usually, inside a class, we declare a data field as private and will provide a set of public SET and GET methods to access the data fields. This is a good programming practice since the data fields are not directly accessible outside the class. We must use the set/get methods to access the data fields. 

An example, which uses a set of set/get methods, is shown below. 

  1. //SET/GET methods  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class MyClass  
  5. {  
  6.     private int x;  
  7.     public void SetX(int i)  
  8.     {  
  9.         x = i;  
  10.     }  
  11.     public int GetX()  
  12.     {  
  13.         return x;  
  14.     }  
  15. }  
  16. class MyClient  
  17. {  
  18.     public static void Main()  
  19.     {  
  20.         MyClass mc = new MyClass();  
  21.         mc.SetX(10);  
  22.         int xVal = mc.GetX();  
  23.         Console.WriteLine(xVal);
  24.     }  
  25. }
The output from above listing is shown below. 
 
 
 
But C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.
  1. <acces_modifier> <return_type> <property_name>  
  2.    {  
  3.       get  
  4.    {  
  5.    }  
  6.       set  
  7.    {  
  8.    }  
  9. }  
Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor. 

For example, the above program can be modified with a property X as follows.

  1. class MyClass  
  2. {  
  3.     private int x;  
  4.     public int X  
  5.     {  
  6.         get  
  7.         {  
  8.             return x;  
  9.         }  
  10.         set  
  11.         {  
  12.             x = value;  
  13.         }  
  14.     }  
  15. }  
The object of the class MyClass can access the property X as follows.
  1. MyClass mc = new MyClass();  
mc.X = 10; // calls set accessor of the property X, and pass 10 as value of the standard field 'value'. 

This is used for setting value for the data member x.

Console.WriteLine(mc.X);// displays 10. Calls the get accessor of the property X. 

The complete program is shown below.

  1. //C#: Property  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class MyClass  
  5. {  
  6.     private int x;  
  7.     public int X  
  8.     {  
  9.         get  
  10.         {  
  11.             return x;  
  12.         }  
  13.         set  
  14.         {  
  15.             x = value;  
  16.         }  
  17.     }  
  18. }  
  19. class MyClient  
  20. {  
  21.     public static void Main()  
  22.     {  
  23.         MyClass mc = new MyClass();  
  24.         mc.X = 10;  
  25.         int xVal = mc.X;  
  26.         Console.WriteLine(xVal);//Displays 10  
  27.     }  
  28. }  
Remember that a property should have at least one accessor, either set or get. The set accessor has a free variable available in it called value, which gets created automatically by the compiler. We can't declare any variable with the name value inside the set accessor.

We can do very complicated calculations inside the set or get accessor. Even they can throw exceptions. 

Since normal data fields and properties are stored in the same memory space, in C#, it is not possible to declare a field and property with the same name. 

Static Properties

C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. 

The following program shows a class with a static property.

  1. //C# : static Property  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class MyClass  
  5. {  
  6.     private static int x;  
  7.     public static int X  
  8.     {  
  9.         get  
  10.         {  
  11.             return x;  
  12.         }  
  13.         set  
  14.         {  
  15.             x = value;  
  16.         }  
  17.     }  
  18. }  
  19. class MyClient  
  20. {  
  21.     public static void Main()  
  22.     {  
  23.         MyClass.X = 10;  
  24.         int xVal = MyClass.X;  
  25.         Console.WriteLine(xVal);//Displays 10  
  26.     }  
  27. }  
Remember that set/get accessor of static property can access only other static members of the class. Also ,static properties are invoking by using the class name. 
 

Properties & Inheritance 

The properties of a Base class can be inherited to a Derived class.

  1. //C# : Property : Inheritance  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class Base  
  5. {  
  6.     public int X  
  7.     {  
  8.         get  
  9.         {  
  10.             Console.Write("Base GET");  
  11.             return 10;  
  12.         }  
  13.         set  
  14.         {  
  15.             Console.Write("Base SET");  
  16.         }  
  17.     }  
  18. }  
  19. class Derived : Base  
  20. {  
  21. }  
  22. class MyClient  
  23. {  
  24.     public static void Main()  
  25.     {  
  26.         Derived d1 = new Derived();  
  27.         d1.X = 10;  
  28.         Console.WriteLine(d1.X);
  29.     }  
  30. }
The output from above listing is shown below.
 
 
 
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.
 

Properties & Polymorphism 

A Base class property can be polymorphically overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

  1. //C# : Property : Polymorphism  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class Base  
  5. {  
  6.     public virtual int X  
  7.     {  
  8.         get  
  9.         {  
  10.             Console.Write("Base GET");  
  11.             return 10;  
  12.         }  
  13.         set  
  14.         {  
  15.             Console.Write("Base SET");  
  16.         }  
  17.     }  
  18. }  
  19. class Derived : Base  
  20. {  
  21.     public override int X  
  22.     {  
  23.         get  
  24.         {  
  25.             Console.Write("Derived GET");  
  26.             return 10;  
  27.         }  
  28.         set  
  29.         {  
  30.             Console.Write("Derived SET");  
  31.         }  
  32.     }  
  33. }  
  34. class MyClient  
  35. {  
  36.     public static void Main()  
  37.     {  
  38.         Base b1 = new Derived();  
  39.         b1.X = 10;  
  40.         Console.WriteLine(b1.X);
  41.     }  
  42. }
The output from above listing is shown below.
 
 
 

Abstract Properties 


A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. 

If the abstract class contains only set accessor, we can implement only set in the derived class. 

The following program shows an abstract property in action.

  1. //C# : Property : Abstract  
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. abstract class Abstract  
  5. {  
  6.     public abstract int X  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11. }  
  12. class Concrete : Abstract  
  13. {  
  14.     public override int X  
  15.     {  
  16.         get  
  17.         {  
  18.             Console.Write(" GET");  
  19.             return 10;  
  20.         }  
  21.         set  
  22.         {  
  23.             Console.Write(" SET");  
  24.         }  
  25.     }  
  26. }  
  27. class MyClient  
  28. {  
  29.     public static void Main()  
  30.     {  
  31.         Concrete c1 = new Concrete();  
  32.         c1.X = 10;  
  33.         Console.WriteLine(c1.X);
  34.     }  
  35. }  
The output from above listing is shown below.
 
 
 
The properties are important features added in language level inside C#. They are very useful in GUI programming. Remember that the compiler actually generates the appropriate getter and setter methods when it parses the C# property syntax.
 

Properties Access Modifiers

 
Access modifiers defines the access level of a property whether a property can be accessed by any caller program, within an assembly, or just within a class.
 
The following table describes access level modifiers. 
  • public - The type or member can be accessed by any other code in the same assembly or another assembly that references it.
  • Private - The type or member can be accessed only by code in the same class or struct.
  • protected - The type or member can be accessed only by code in the same class, or in a class that is derived from that class.
  • internal - The type or member can be accessed by any code in the same assembly, but not from another assembly.
  • protected internal - The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.
  • private protected - The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.

Automatically Implemented Properties

 
A typical implementation of a public property looks like Listing . The default implementation of a property needs a getter and setter.
  1. private string name;  
  2. public string Name  
  3. {  
  4.    get { return this.name; }  
  5.    set { this.name = value; }  
  6. }  
Auto-implemented properties in C# makes code more readable and clean if there is no additional calculation needed. The above code of Listing can be replaced by the following one line of code in Listing
  1. public string Name { getset; }  
In case of auto-implemented properties, the compiler creates a private field variable that can only be accessed through the property's getter and setter.
 
Code listed in Listing is a class with several auto-initialized properties.
  1. using System;  
  2. class Author {  
  3.     // Read-write properties    
  4.     public string Name {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Publisher {  
  9.         get;  
  10.         set;  
  11.     }  
  12.     public string Book {  
  13.         get;  
  14.         set;  
  15.     }  
  16.     public Int16 Year {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public double Price {  
  21.         get;  
  22.         set;  
  23.     }  
  24.     public string PriceInString {  
  25.         get {  
  26.             return string.Format("${0}", Price);  
  27.         }  
  28.     }  
  29.     // Read-only properties    
  30.     public string Names {  
  31.         get;  
  32.     }  
  33.     // Initialization of a property    
  34.     public double AuthorCount {  
  35.         get;  
  36.         private set;  
  37.     } = 99;  
  38.     // Class constructor    
  39.     public Author(string name, string publisher, string book, Int16 year, double price) {  
  40.         Name = name;  
  41.         Publisher = publisher;  
  42.         Book = book;  
  43.         Year = year;  
  44.         Price = price;  
  45.     }  
  46.     // Public methods    
  47.     public string AuthorDetails() {  
  48.         return string.Format("{0} is an author of {1} published by {2} in year {3}. Price: ${4}", Name, Book, Publisher, Year, Price);  
  49.     }  
  50.     public double CostOfThousandBooks() {  
  51.         if (Price > 0) return Price * 1000;  
  52.         return 0;  
  53.     }  
The code in Listing is creates an instance of the class and calls its methods and properties.
  1. class Program   
  2. {  
  3.     static void Main()   
  4.   {  
  5.         Author author = new Author("Mahesh Chand""Apress""Programming C#", 2003, 49.95);  
  6.         Console.WriteLine(author.AuthorDetails());  
  7.         Console.WriteLine("Author published his book in {0}", author.Year);  
  8.         author.Price = 50;  
  9.         Console.WriteLine(author.CostOfThousandBooks().ToString());  
  10.         Console.ReadKey();  
  11.     }  
  12. }