subtraction of two double properties []

3

I have a class called funcoes.cs

I need to create a property that stores the initial X, Y, and X, Y final values, thought of:

    public  double[] PosicaoInicialXY { get; set; }
    public  double[] PosicaoFinallXY { get; set; }

then it would send the parameters like this:

double[] valoresFinalXY = new double[2];
            valoresFinalXY[0] = 40;
            valoresFinalXY[1] = 5;
            funcoes.PosicaoFinallXY = valoresFinalXY;

and also to the starting position

Doubt: How could I create a new property that would subtract X, Y initial - X, Y final?

 double[] resultado = this.PosicaoInicialXY - this.PosicaoFinallXY; //??? não deu certo
    
asked by anonymous 24.03.2014 / 21:18

2 answers

2

A property with a getter to do this does not solve?

public double[] DifXY
{
    get 
    {
        return new[] {
            this.PosicaoInicialXY[0] - this.PosicaoFinallXY[0],
            this.PosicaoInicialXY[1] - this.PosicaoFinallXY[1],
            };
    }
}

EDIT: explanation of what is being done:

The getter above returns a new array with two elements, the first one calculates the respective values of index 0, and the second calculates the respective values of indexes 1.

When using new[] { a, b, c, ... } , you are actually creating an array, which is of the same type as the elements a, b, c, and so on. If both are double , an array of type double[] will be created.

Example:

double[] array = new [] { 1.0, 2.0, 3.0 }; // criando array com os valores
    
24.03.2014 / 21:28
2

One workaround would be to create a type that specializes in storing positions:

public struct Point
{
    private double x, y;

    public Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    public double X { get { return x; } }
    public double Y { get { return y; } }

    public static Point operator -(Point a, Point b)
    {
        return new Point(a.x - b.x, a.y - b.y);
    }
}

See I'm using operator overload, to set what the minus sign does.

So in your class, instead of working with arrays, you could use the specialized type to do what you want.

public class MinhaClasse
{
    public Point PosicaoInicial { get; set; }
    public Point PosicaoFinal { get; set; }

    public Point Diferenca
    {
        get { return this.PosicaoInicial - this.PosicaoFinal; }
    }
}

The advantage of this method is that it reads easier to understand, and you are creating a type that encapsulates the functionality needed to manipulate positions.

The downside is that it will be one more type in your code base.

    
24.03.2014 / 21:47