How to do mathematical operations with a struct?

Asked

Viewed 171 times

3

I have the following structure:

public struct vetor
{
    public float X, Y;
    public vetor(float X, float Y)
    {
        this.X = X;
        this.Y = Y;
    }
}

And this code:

Vars.vetor _visao;
Vars.vetor _recoil; //Os 2 possuem valores, eu tirei para ilustrar melhor

Vars.vetor towrite = _visao - _recoil * 2.0f;

But he is returning me the following error:

CS0019 error The "*" operator cannot be applied to type operands "Vars.vetor" and "float"

I wonder if you could make this code work as follows:

towrite.X = _visao.X - _recoil.X * 2.0f;
towrite.Y = _visao.Y - _recoil.Y * 2.0f;

I thought this was impossible until I saw that class Vector2 supports this kind of thing. That is, how it does it?

1 answer

4


This is done with methods operators.

using static System.Console;

public class Program {
    public static void Main() {
        var vetor = new Vetor(3, 4);
        var vetor2 = vetor * 2f;
        WriteLine($"X = {vetor2.X}, Y = {vetor2.Y}");
    }
}

public struct Vetor {
    public float X, Y;
    public Vetor(float X, float Y) {
        this.X = X;
        this.Y = Y;
    }
    public static Vetor operator *(Vetor left, float right) => new Vetor(left.X * right, left.Y * right);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Obviously you need to make the other operators, but the technique is this.

Source for all. NET classes. And no . NET Core.

  • Great! I didn’t know this kind of method. =)

Browser other questions tagged

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