How to Overload Operators

1

You can Overload operators but I can not understand clearly ¿Como es su sintaxis correctamente y simple? y ¿Para Que puede ser utilizado? surfing the web found different very confusing examples that are not clear which causes me a higher level of confusion to use this operator to overload operators the only thing I know that it is for Overload of operators and that something like this is declared in addition when I write it, it shows me that its syntax is wrong.

public static Metodo operator+(int a, int b)
 {

 }
    
asked by Diego 11.04.2017 в 01:23
source

1 answer

3

For example, if I want to add two integers (int) it gives me another integer, if I want to divide two integers it gives me a fraction (single?), if I want to add two dates it gives me a date and so (in case of the dates is not overloaded I think it's datetime.add), it's called binary operation (I combine two things and it gives me one) and what we use are the binary operators

Well now I want to add two crazy things that the language does not contemplate, for example I add two people and one person gives me:

Persona Jose = new Persona(70, 40);
Persona Juan = new Persona(80, 30);
Persona Pedro = Jose + Juan;

this c # does not allow us but if we overload the operated, in this case the + that is binary that takes 2 objects and returns 1 and we tell you what to do in that case:

public class Persona
{
    public int peso;
    public int edad;

    public Persona(int p, int e)  // constructor
    {
        peso = p;
        edad = e;
    }

    // sobrecargamos el + que toma 2 Personas y devuelve Persona:
    public static Persona operator+(Persona a, Persona b)
    {
        return new Persona(a.peso + b.peso, a.edad + b.edad);
    }
}

Now we realize that Pedro weighs 150kg and has an age of 70 years, but it is very useful for concrete things for example to take averages or if I want to know how much weight an asensor carries then I add the people :), and things like that .

It is not widely used. it's really a function, if you do it with the usual format, it also works.

Persona Pedro = Jose.Agregar(Juan).Agregar(Julio)
    
answered by 11.04.2017 / 01:54
source