Go Back   Computer Forums > General Computing > Programming
Click Here to Login
Join Computer forums Today


Reply
 
Thread Tools Search this Thread Display Modes
 
Old 01-15-2009, 04:44 PM   #1
Baseband Member
 
Join Date: Nov 2008
Posts: 91
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:

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?
__________________

BobLewiston is offline   Reply With Quote
Old 01-15-2009, 05:03 PM   #2
Guru
 
JogaBonito1502's Avatar
 
Join Date: Jan 2008
Location: U.S.
Posts: 7,841
Default Re: the "this" reference & indexers

I'm not familiar with the "this" command. I assume you're using C#. As far as "this", I think you use it to refer to the current class. So on the first instance, instead of typing "citizen" you type "this".

See if this helps (lol)
__________________

JogaBonito1502 is offline   Reply With Quote
Old 01-15-2009, 05:11 PM   #3
Baseband Member
 
Join Date: Nov 2008
Posts: 91
Default Re: the "this" reference & indexers

attention, JogaBonito1502:

Yes, sort of. "this" refers to the current object, and I know how to use it to refererence individual objects, as you can see from my code. What I was looking for was the actual code to make it reference an array of objects.
BobLewiston is offline   Reply With Quote
Old 01-15-2009, 05:23 PM   #4
Guru
 
JogaBonito1502's Avatar
 
Join Date: Jan 2008
Location: U.S.
Posts: 7,841
Default Re: the "this" reference & indexers

Man, I'm getting really confused with no indentation. Use the code button to paste code so it indents. use "Go Advanced" to do this.
JogaBonito1502 is offline   Reply With Quote
Old 01-15-2009, 06:19 PM   #5
Baseband Member
 
Join Date: Nov 2008
Posts: 91
Default attention, JogaBonito1502:

Note: the following has been slightly editted from my previous post to better describe my problem.

Subject: controlling access to private fields of an array of objects

Can anybody give me a hint about how to put these two techniques together?

I can use the "get" and "set" accessors of an individual object's properties to control access to the object's private fields:

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 the "this" reference and indexers to make an array of objects:

Code:
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]    // here's the "this" reference
        {
            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.
BobLewiston is offline   Reply With Quote
Old 01-15-2009, 06:28 PM   #6
Guru
 
JogaBonito1502's Avatar
 
Join Date: Jan 2008
Location: U.S.
Posts: 7,841
Default Re: the "this" reference & indexers

Did my post not go through? Weird...

Anyways...here's what I said:

Isn't "this" used in refference to the current class? So if your writing a line under Class Citizen instead of typing citizen.xxxx don't you type this.xxx?
JogaBonito1502 is offline   Reply With Quote
Old 01-20-2009, 11:19 AM   #7
In Runtime
 
Daeva's Avatar
 
Join Date: Dec 2005
Posts: 407
Send a message via AIM to Daeva Send a message via MSN to Daeva Send a message via Yahoo to Daeva
Default Re: the "this" reference & indexers

If I am understanding correctly, this should help.

The keyword "this" is a reserved word, as a result, you can't create a method with the name "this". Also, by making the variables private, you are denying access to them by any class outside of itself. If you wanted to get the age of the person in the array, you wouldn't use the this reference, you would fully qualify it by saying:
citizen[0].Age;

Here is some example code I wrote the should get done what you're trying to do, while using "this" references where appropriate.

Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace CitizenExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Citizens myCitizens = new Citizens();
            myCitizens.Add(new Citizen("Dave", 22));
            myCitizens.Add(new Citizen("Steve", 25));
            for (int i = 0; i < myCitizens.Count; i++)
            { // loop through all citizens added up to this point
                Console.WriteLine(myCitizens[i].ToString());
            } // end for loop
            Console.ReadLine();
        } // end method Main
    } // end class Program

    //By inheriting from the Generic List<ObjectType> class, we can add as many citizens
    //to the list as we want, without setting a specific size of the array
    public class Citizens : List<Citizen> // we inherit from the generic list object
    {
        public Citizens()
        {
        } // end constructor

        
    }
    //The class citizen is what the Citizens class is made up of
    public class Citizen
    {
        private String _name;
        private int _age;

        public Citizen(String name, int age)
        {
            // assign the initial values
            this.Age = age;
            this.Name = name;
        } // end void Citizen

        public int Age {
            get { return _age;} // end get
            set {
                try {
                   if (value < 0) {
                       throw new Exception("Age cannot be less than zero!");
                   } else {
                       _age = value;
                   } // end if/else
                } catch(Exception ex) {
                    Console.WriteLine(ex.Message + Environment.NewLine);
                } // end try/catch
            } // end set
        } // end int Age

        public String Name
        {
            get { return _name; }
            set
            {
                try
                {
                    if (value.Length <= 0)
                    {
                        throw new Exception("The citizen must have a name!");
                    }
                    else
                    {
                        _name = value;
                    } // end if/else
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + Environment.NewLine);
                } // end try/catch
            } // end set
        } // end String name

        public override string ToString()
        {
            return "This citizen's name is " + this.Name + " and this person is " + this.Age + " years old." + Environment.NewLine;
        } // end ToString
    } // end Class Citizen
} // end Namespace
__________________

__________________
**Official Self-proclaimed glorified excessive (insert additional adjectives here) post editor/modifier.
Edit = Best feature ever
http://www.twitter.com/xDaevax
Daeva is offline   Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off



All times are GMT -5. The time now is 05:48 AM.


Powered by vBulletin® Version 3.8.8 Beta 4
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Search Engine Friendly URLs by vBSEO 3.6.0