View Single Post
Old 01-15-2009, 04:48 PM   #1 (permalink)
BobLewiston
 
Junior Techie

Join Date: Nov 2008

Posts: 79

BobLewiston is on a distinguished road

Default the "this" reference & indexers

Can anybody give me a hint about how to put these two techniques together? I can use the "this" reference to control access to the private fields of an individual object:
Code:
using System;
namespace MyNamespace
{
    class Program
    {
        static void Main ()
        {
            Citizen citizen = new Citizen ();

            citizen.Name = "Larry Fine";
            citizen.Age = 89;

            Console.WriteLine ("{0}, {1}\n\n\n", citizen.Name, citizen.Age);
        }
    }

    class Citizen
    {
        private string name;
        private int age;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

And I can use indexers to make an array of objects:

using System;
namespace MyNamespace
{
    class Program
    {
        static void Main ()
        {
            Citizen citizen = new Citizen ();

            citizen [0] = "Larry Fine";
            citizen [1] = "Buster Douglas";
            citizen [2] = "Mortimer Snerd";
            citizen [3] = "Horace Greeley";
            citizen [4] = "Ornette Coleman";

            Console.WriteLine ("{0}\n{1}\n{2}\n{3}\n{4}\n", citizen [0], 
		          citizen [1], citizen [2], citizen [3], citizen [4]);
        }
    }

    class Citizen
    {
        private string [] name = new string [5];

        public string this [int i]
        {
            get { return name [i]; }
            set { name[i] = value; }
        }
    }
}
But I can't figure out how to put the two techniques together to control access to the private fields of an array of objects. The solution is probably staring me right in the face, but I don't see it. Any help?

P.S. This is a console application, obviously.

P.P.S. BTW, what happened to all my indentation?

Last edited by Mak213; 01-24-2009 at 02:40 PM. Reason: added code tags
BobLewiston is offline