Breaking News

Comparison between Properties and Indexers in C#

 
Comparison between Properties and Indexers in csharp

Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties. Except for the differences shown in the given below, all of the rules defined for property accessors apply to indexer accessors as well.

 
Property:
 
? Identified by its name.

? Accessed through a simple name or a member access.

? Can be a static or an instance member.

? A get accessor of a property has no parameters.

? A set accessor of a property contains the implicit value parameter.

 
Indexer:
 
? Identified by its signature.

? Accessed through an element access.

? Must be an instance member.

? A get accessor of an indexer has the same formal parameter list as the indexer.

? A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

 
Practical Example (Indexer):
 
testIndexer.cs
 
using System;
using System.Collections.Generic;
using System.Text;

namespace testIndexer
{
    class MyPrevExp
 	{ 
  		private string[] myCompanies = new string[10]; 

  		//index creation
  		public string this[int index]
  		{ 
   			get
   			{
    				if(index <0 || index >= 6)
     					return "null"; 
    				else
     					return myCompanies[index];    
   			} 
   			set
   			{
    				if(!(index <0 || index >= 10))
     					myCompanies[index] = value;
   			} 
  		} 
 	}
    
    class Program
    {
        public static void Main(string[] args)
        {
            testIndexer.MyPrevExp indexerObj = new testIndexer.MyPrevExp();  
   			indexerObj[0] = "eBIZ.com Pvt. Ltd.";
   			indexerObj[3] = "HCL";
            indexerObj[5] = "ACC";
   			for(int i=0; i<10; i++)
   			{    
    				Console.WriteLine("My Companies{0}:  {1}",    i,indexerObj[i]);
   			}
            Console.ReadLine();
        }
    }
}
 
The Output is:
 
img
 

Check Also

Exceptions In C#

System.Exception is the base class for all other exceptions. Below this level are the System.ApplicationException …