How to use object retrieved from method

I made a method to create a polygon with hexagonal shape and retrieve it as an object but I don't know how to use said object. The code is as follows:

    public object Hexagon()
    {
        float h;
        float r;
        int x = 20;
        int y = 20;
        int s = 10;

        h = HexOperations.ConvertToFloat(HexOperations.Calc(s));
        r = HexOperations.ConvertToFloat(HexOperations.Calc(s));

        Point[] vert= new Point[6];

        vert[0] = new Point(x, y);
        vert[1] = new Point(x + s, y);
        vert[2] = new Point(x + s + h, y + r);
        vert[3] = new Point(x + s, y + r + r);
        vert[4] = new Point(x, y + r + r);
        vert[5] = new Point(x - h, y + r);

        Polygon pol = new Polygon();

        System.Windows.Media.PointCollection pointC = new System.Windows.Media.PointCollection();

        pointC.Add(vert[0]);
        pointC.Add(vert[1]);
        pointC.Add(vert[2]);
        pointC.Add(vert[3]);
        pointC.Add(vert[4]);
        pointC.Add(vert[5]);

        pol.Points = pointC;

        pol.Stroke = Brushes.Black;

        return pol;
    }

If I add ´MainGrid.Children.Add(pol)´ before the return I can see the hexagon printed on the Grid ´MainGrid´ but I just don't know how to use it outside the said method. I've tried this:

    MainGrid.Children.Add(Hexagon());

Which gives me the error "cannot convert from ´object´ to System.Window.UIElement".

Also tried:

    Polygon poly = new Hexagon();

Which say "a new expression requires (). [], {}, ;, after type".

And:

    Hexagon poly = new Hexagon();

And this obviously gave me the finger. I just don't know what else to try. Probably because I'm making an elemental mistake with my approach but, anyways, thank you in advance.

Jon Skeet
people
quotationmark

Your method is declared to return object - but you know it's a Polygon, so assuming you want callers to rely on it returning a Polygon (which seems reasonable) you should change the return type.

public Polygon Hexagon()

You also need to call the method, instead of either trying to use it as a type name with new, or passing it directly:

Polygon polygon = Hexagon();
// Use polygon here

I would also recommend:

  • Naming the method with a verb, e.g. CreateHexagon
  • Learning the basics of C# in console apps rather than GUIs - it's a lot simpler that way, which lets you focus on the one thing you're trying to learn, without being confused by the huge complexity of UI work

people

See more on this question at Stackoverflow