Properties and Indexers in C#
page 1 of 1
Published: 28 Mar 2006
Unedited - Community Contributed
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.
by Joydip Kanjilal
Feedback
Average Rating: 
Views (Total / Last 10 Days): 36319/ 54

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!



User Comments

Title: very helpful   
Name: mirnalini
Date: 2006-12-15 4:45:23 AM
Comment:
This Article is very nice and excellent description for indexers and properdies.And it's very useful one fo the beginner's.
Title: Brief and upto the mark. Nice artcle   
Name: Raju
Date: 2006-11-21 4:22:06 AM
Comment:
I hade littel confusion to impliment Indexers. After reading this, I am very much confident to use Indexers in Application.
Title: Good Description   
Name: swathy
Date: 2006-11-16 2:32:46 AM
Comment:
This is really good description.
Title: Excellent   
Name: saranyan
Date: 2006-11-01 7:10:09 AM
Comment:
Sir,

I thank you for writing this article .I have gone through some articles before reading your article.But,I faced a little confusion.After finished reading this artcle,I got my doubts cleared.Thank you sir.
Title: very nice   
Name: shikha gupta
Date: 2006-10-28 2:47:17 AM
Comment:
Nice artical with good examples.
Title: Very Nice   
Name: Sudhakar.N.V
Date: 2006-08-04 12:58:57 AM
Comment:
This is very Nice for properties and indexers. it's easily understandable.
Title: Supportive and easy   
Name: Rashid Ahmad
Date: 2006-07-25 12:36:03 AM
Comment:
An easy approach has adopted to explain the theme.
Title: Very Good   
Name: Alefiya
Date: 2006-07-11 6:08:24 AM
Comment:
This article is really good.It has cleared my doubts about indexers and properties
Title: Great   
Name: Andrei
Date: 2006-07-08 11:35:20 AM
Comment:
Very clear article that sheds light on the subject of properties and indexers
Title: Nice   
Name: Mesut
Date: 2006-06-14 5:52:21 AM
Comment:
Nice work.
Title: i like it   
Name: huyvn
Date: 2006-06-14 3:09:40 AM
Comment:
very understand, and very to use. thanks man.
Title: Excellent   
Name: Sudarshan
Date: 2006-04-26 9:49:40 AM
Comment:
Excellent and simple. Great article. Keep those coming dude !!!
Title: Excellent   
Name: Santhakumar.P
Date: 2006-04-15 5:12:25 AM
Comment:
This Article is very nice and excellent description for indexers and properdies.And it's very useful one fo the beginner's.
Title: goog   
Name: vasanth
Date: 2006-04-01 7:24:18 AM
Comment:
This is good description on indexers and property
Title: Nice   
Name: Kalyan
Date: 2006-03-29 9:25:05 AM
Comment:
This is simply a wonderful article. Good work!
Title: Good   
Name: Lakshmi
Date: 2006-03-28 11:48:44 PM
Comment:
Article is outstanding.
Title: Good   
Name: Manashi
Date: 2006-03-28 7:43:20 AM
Comment:
The article is nice with good examples.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-03-23 4:15:52 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search