subtraction of two double properties[]

Asked

Viewed 134 times

3

I have a class called functions.Cs

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

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

then send the parameters like this:

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

and also for the incial position

Doubt: How could you create a new property that subtracts initial X,Y - final X,Y ?

 double[] resultado = this.PosicaoInicialXY - this.PosicaoFinallXY; //??? não deu certo

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 above getter returns a new array with two elements, the first of which calculates the respective index values 0, and the second of which calculates the respective index values 1.

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

Example:

double[] array = new [] { 1.0, 2.0, 3.0 }; // criando array com os valores
  • Perfect, just one more question, why re-turn new[] ?

2

An alternative solution would be to create a type specialized 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);
    }
}

Note that I am using operator overload, to define what the subtraction signal does.

So in your class, instead of working with arrays, you could use the specialized type to do whatever 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 for what reads it becomes easier to understand, besides you are creating a type that encapsulates the functionalities necessary for handling positions.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.