Click to See Complete Forum and Search --> : Indexers,parameter as string


ganmath
April 4th, 2001, 01:59 PM
the following program works fine when i use index as int but gives error
when used as it as string
Can anybody explain me how to modify the following program so that
index can be used as string or any other type except int

using System;
public class Coordinate{
double[] cdnate = new double[2];
public double this[string index]
{
get{
return cdnate[index];
}
set{
cdnate[index] = value;
}
}

public static void Main(string[] arg){

Coordinate p1 = new Coordinate();
Coordinate p2 = new Coordinate();
Coordinate p3 = new Coordinate();

p1["X"] =2; p1["Y"] =3; p2["X"] =5; p2["Y"] =6;
p3["X"] =p1["X"]+p2["X"];
p3["Y"] =p1["Y"]+p2["Y"];

Console.WriteLine("({0},{1}) + ({2},{3} ) = ({4},{5}) ",p1["X"],p1["Y"],p2["X"],p2["Y"],p3["X"],p3["Y"]);
}

}


// (2,3)+(5,6)=(7,9) this is addition of two coordinates

kswoll
April 5th, 2001, 07:21 PM
Your lines:

return cdnate[index];
cdnate[index] = value;

Are invalid because "cdnate" is an array and the type of "index" is a string. Array elements are referenced by integer index (obviously). You could try changing the type of "cdnate" to a Hashtable if you really want to use strings.

Kirk

Martin Perkins
April 6th, 2001, 03:36 AM
I think you need to do the following
public double this[string index]
{
get
{
if (index == "X")
{
return cdnate[0];
}
else
{
return cdnate[1];
}
}
set
{
if (index == "X")
{
cdnate[0] = value;
}
else
{
cdnate[1] = value;
}
}
}