Pages

Tuesday, June 5, 2012

Properties and Indexers in C#

Abstract
Properties are known as smart fields and enable access to the fields of a class. Indexers are also called smart arrays in C# and can be used to use an object as an array. This article discusses both of these concepts with simple code examples.


Property
A property is like a "virtual field" that contains get and set accessors and provides an interface to the members of a class. They can be used to get and set values to and from the class members. Properties can be static or instance members of a class. The get accessor does not accept any parameter; rather it returns the value of the member that it is associated with. The set accessor contains an implicit parameter called 'value'. The following code example illustrates a simple property.

Listing 1 - Implementing properties

using System;
namespace ConsoleApplication
{
  class Test
  {
    private int number;
    public int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test test = new Test();
      test.MyProperty = 100;
      Console.WriteLine(test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows a static property. The static property MyProperty can be accessed without instantiating the class. A static property can access static members of a class only.

Listing 2 - Implementing a static property
using System;
namespace ConsoleApplication
{
  class Test
  {
    private static int number;
    public static int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test.MyProperty = 100;
      Console.WriteLine(Test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows how the visibility of the get and the set accessors has been restricted to the current assembly only by using the keyword "internal".

Listing 3 - Restricting the visibility
public class Employee
{
  private int empID;
  private string empName;
 
  internal int ID
  {
    get { return empID; }
    set { empID = value; }
  }
  internal string Name
  {
    get { return empName; }
    set { empName = value; }
  }
}
 
public class Test
{
  public static void Main(string[]args)
  {
    Employee emp = new Employee();
    emp.Name = "Joydip";
    emp.ID = 259;
    System.Console.WriteLine("The id is:" + emp.ID);
    System.Console.WriteLine("The name is:" + emp.Name);
  }
}
The keyword “internal” implies that the property's ID and Name can be accessed from the current assembly only as they are “internal” to the assembly in which they have been declared.
----------------------------------------------------------------------------------------------------
Indexer
Indexers are also called smart arrays in C# and can be used to treat an object as an array. An indexer allows an instance of a class or a struct to be indexed as an array, which is useful for looping or iterating or data binding operations.
The following is the syntax of an indexer declaration.
<Modifier> <Return type> this[arguments]
{
  get { }
  Set { }
}
The modifier can be one of the following
·         private
·         public
·         protected
·         internal
All indexers should accept at least one parameter. Indexers cannot be static. This is because static methods do not have access to ‘this’. The ‘this’ keyword indicates an instance of the current class. Look at the code given below.

Listing 4 - A simple indexer
namespace ConsoleApplication
{
  using System;
  class Employee
  {
    private string[]name = new string[10];
    public string this[int index]
    {
      get { return name[index]; }
      set { name[index] = value; }
    }
  }
 
  class Test
  {
    public static void Main()
    {
      Employee emp = new Employee();
      emp[0] = "Joydip";
      emp[1] = "Manashi";
      emp[2] = "Jini";
      Console.WriteLine("The namesare:--");
      for (int i = 0; i < 3;Console.WriteLine(emp[i++]))
        ;
      Console.ReadLine();
    }
  }
}
The output of the program is
The names are:--
Joydip
Manashi
Jini

Indexers in inheritance
The indexers of the base class are inherited to its derived classes. This is illustrated in the code shown below.

Listing 5 - Indexers in inheritance
using System;
class Base
{
  public int number;
  public int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base{}
class Test
{
  public static void Main()
  {
    Derived d = new Derived();
    d[0] = 500;
    Console.WriteLine("The value is: "+ d[0]);
  }
}
The program displays the string “Set of the base class. Get of the base class. The value is: 500”.
Indexers can be polymorphic. We can have the same indexer in the base and the derived classes. Such indexers are ‘overridden indexers’ and require the keyword virtual to be stated in their declaration in the base class. The following program illustrates this.

Listing 6 - Indexers can be polymorphic
using System;
class Base
{
  protected int number;
 
  public virtual int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get
    {
      Console.Write("Get of the derivedclass.");
      return base.number;
    }
    set
    {
      Console.Write("Set of the derivedclass.");
      base.number = value;
    }
  }
}
 
class Test
{
  public static void Main()
  {
    Base obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is “Set of the derived class. Get of the derived class. The value is: 500”.

Abstract indexers
Indexers can be abstract. We can have abstract indexers in a base class that need to be implemented by the class subclassing (inheriting from) it. The abstract indexer like an abstract method does not contain any code in its get or set. This is shown in the example below.

Listing 7 - Indexers can be abstract
using System;
abstract class Base
{
  protected int number;
 
  public abstract int this[int index]
  {
    get;
    set;
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get { return number; }
    set { number = value; }
  }
}
 
class Test
{
  public static void Main()
  {
    Derived obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is "The value is: 500".

Comparison between properties and indexers
Properties are accessed by names but indexers are accessed using indexes. Properties can be static but we cannot have static indexers. Indexers should always be instance members of the class. The get accessor of a property does not accept any parameter but the same of the indexer accepts the same formal parameters as the indexer. The set accessor of a property contains an implicit parameter called "value". The set accessor of an indexer contains the same formal parameters as that of the indexer and also the "value" as an implicit parameter.

Conclusion
Properties and indexers are two of the most important concepts in C#. This article has discussed both these concepts with code examples. I would highly appreciate any comments and or suggestions from the readers related to this article. Please post your comments and or suggestions if you have any. Happy reading!

No comments: