Working with Property Indexers in C#

by kiranpvn kumar on 2/8/2012 4:56:03 AM
Rated 1 from 1 votes
Brief: Demonstrates on defining,instantiating and using Property Indexers using a simple example.
Posted to: Basics of Object Oriented Programming in .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

When we want content/data in a class to be exposed in the form an array, but making it accessible directly using the instance name (of the same class), we will create "Property Indexers".  In this case, the instance of the class will be working similar to that of an Object Array (of the same class). 

Attached sample demonstrates the following:
  • Creating an array inside a class
  • Making array inside a class exposed as Property Indexer
  • Creating an instance of the class (which has Property Indexer) using "Array" syntax
  • Accessing the data inside the class in the form of an array using Property Indexer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Indexers
{
    class Friends
    {
        private string[] names; // Private data member, its an array
        public Friends(int n)
        {
            names = new string[n];
            for (int i = 0; i < n; i++)
                names[i] = "empty";
        }
        public string this[int i]       //Its an indexer and looks like property definition
        {
            set
            {
                names[i] = value;
            }
            get
            {
                return names[i];
            }
        }
        public void ShowFriendsList()
        {
            for (int i = 0; i < names.Length; i++)
                Console.WriteLine(names[i]);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Friends FriendsofJames = new Friends(5);
 
            //Default friends list is empty, you can view by using follwoing statements
 
            for (int i = 0; i < 5; i++)
                Console.WriteLine("{0}", FriendsofJames[i]);
 
            FriendsofJames[0] = "Jagadeesh";    // Object behaves like an array
            FriendsofJames[1] = "Kiran";
            FriendsofJames[2] = "Krishna";
            FriendsofJames[3] = "Prasad";
            FriendsofJames[4] = "Ravi Varma";
 
            for (int i = 0; i < 5; i++)
                Console.WriteLine("{0}", FriendsofJames[i]);
        }
    }
}

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 1 from 1 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following