indexer question

G

george r smith

Hi all,

I found this example in the help and thought this is great. But I can not
figure out how to
iterate thru the array and print out the values in the array.
Do I use a foreach (I tried could not get that to work) or a for loop (same
result)

my test harness below works so I know I am getting values into the grid,
which is a two
dimensioned array with an indexer[char,int]
a little code example please
thanks
grs

public static void Main()
{
Grid aGrid = new Grid();
aGrid['A',1] = 1;
Console.WriteLine(aGrid['A',1].ToString());

*** so here how do I loop thru the array

=======================
class Grid
{
const int NumRows = 26;
const int NumCols = 10;
int[,] cells = new int[NumRows, NumCols];
public int this[char c, int col]
{
get
{
c = Char.ToUpper(c);
if (c < 'A' || c > 'Z')
{
throw new ArgumentException();
}
if (col < 0 || col >= NumCols)
{
throw new IndexOutOfRangeException();
}
return cells[c - 'A', col];
}
set
{
c = Char.ToUpper(c);
if (c < 'A' || c > 'Z')
{
throw new ArgumentException();
}
if (col < 0 || col >= NumCols)
{
throw new IndexOutOfRangeException();
}
cells[c - 'A', col] = value;
}
}
}
 
G

george r smith

Got it, is this the standard way or is there another.
george

for (char aChar = 'A'; aChar < 'Z'; aChar++)
for (int i = 0; i < 10; i++)
Console.WriteLine(aGrid[aChar,i]);
 
J

Jeffrey Tan[MSFT]

Hi George,

Thanks for posting in this group.
Foreach statement can be used to loop through arrays or collections.
For example, in Grid class, you can expose a print method, which will use
foreach to loop through cells array. Like this:
public void print()
{
foreach(int obj in cells)
{
Console.WriteLine(obj.ToString());
}
}

Also, you can treat Grid class as a collection, but you must implement
GetEnumerator method.
For more information to use foreach to loop through collection , please
refer to:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/
vclrfusingforeachwithcollections.asp

Hope this helps,
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top