Properties and Indexers in C#

Properties:

In Object-Oriented Systems, it’s not to permit any direct access to data members because of the implications of integrity. It provides some special methods that are known as Accessor Methods. It is used to access data members. We must use only these methods to set or retrieve the values of these members. C# provides a mechanism known as Properties that have the same capabilities as accessor methods.

But it is much more elegant and simple to use. Using a property, a programmer can get access to data members as though they are public fields. So, Properties are sometimes referred to as ‘smart fields‘.

Example:

using System;
class Number
{
private int n;
public int Num // property
{
get
{
return n;
}
set
{
n=value;
}
}
}
class Test
{
public void static Main()
{
Number n1=new Number();
n1.Num=50;
int k=n1.Num;
Console.WriteLine("Number is: "+k);
}
}

A property can omit either a get clause or a set clause. A property that has only a getter is called a read-only property and it has only a setter is called a write-only property. A write-only property is very rarely used.

Features of Properties:

1. A get clause uses code to calculate the value of the property using other fields and returns the results. It means that properties are not simply tied to data members and they can also represent dynamic data.

2. Properties are inheritable like methods. We can use the modifiers abstract, virtual, and new and override them appropriately. So that the derived classes can implement their versions of properties.

3. The static modifier can be used to declare properties that belong to the whole class rather than to a specific instance of the class.

Indexers:

Indexers are location indicators that are used to access class objects, just like accessing elements in an array. It is very useful in most cases where a class is a container for other objects. An indexer looks like a property and it is written the same way a property is written.

Features of Indexers:

1. The indexers take an index argument and look like an array.
2. The indexer is declared using the name this.
3. The indexer is implemented through get and set accessors for the [] operator.

Example:

using System;
using System.Collections
class List
{
private string[] ITCompanies=new string[10];
public string this[int index]
{
get
{
if(index<0 || index>=7)
return "Empty";
else
return ITCompanies[index];
}
set
{
if(!(index<0 || index>=7)
ITCompanies[index]=value;
}
}
}
class Temp
{
public static void Main()
{
List l1=new List();
l1[0]="IBM";
l1[2]="Infosys";
l1[5]="Wipro";
l1[7]="HCL";
l1[10]="TCS";
Console.WriteLine("Best IT Companies in India./n");
for(int i=0; i<=10; i++)
{
Console.WriteLine("The name of IT Company at index{0}:
{1}",i,l1[i]);
}
}
}