-2

I want to swap the field in the ConvexHull class just like swap( points[0], points[1] ).

How do I have to do?

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        Point.swap ( ref points[ 0 ], ref points[ 1 ] );  //Error!!
    }
}

public class Point
{
    private double x, y;

    Point () { x = y = 0; }
    public static void swap(ref Point a, ref Point b) {
        Point c = a;
        a = b;
        b = c;
    }
}
BokukPark
  • 29
  • 5

2 Answers2

1

When you index an element of List<T> you are actually accessing the this indexer, which is a kind of property (i.e. has getter and setter methods). You can only pass variables as ref or out, not properties.

In your scenario, perhaps you want something more like this:

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        swap(0, 1);  //No error!!
    }

    private void swap(int i, int j)
    {
        Point point = points[i];

        points[i] = points[j];
        points[j] = point;
    }
}

A more general solution might look like this:

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        points.SwapElements(0, 1);
    }
}

static class Extensions
{
    public static void SwapElements<T>(this List<T> list, int index1, int index2)
    {
        T t = list[index1];

        list[index1] = list[index2];
        list[index2] = t;
    }
}

In either case, the correct approach is to provide the code that is actually swapping values with access to the List<T> object itself, so that it can access the indexer property to accomplish the swap.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
0

Throw pretty much all of that away. You can't pass properties or list objects by ref. I notice there is nothing initially populating those points. Populate your List of Points, then call a function in your ConvexHull class to SwapPoints(int point1idx, int point2idx) and write the code there to do the swap.

On the Point class, expose X and Y, and drop the swap routine from there as it will never work.