How to create operators in C#?

Asked

Viewed 238 times

9

How to create an operator in C#? For example,

There are operators like:

* multiplicacao
/ divisao
% percentual

The question is:

How can I create my own operator? For example:

100 ~ 2 = 200.8

Where ~ would be my operator who would do something like:

A ~ B = ((A * 2) + (B * 2)) / (5) 
100 ~ 2 = ((100 * 2) + (2 * 2)) / 5 = 200.8
  • 1

    Creating an operator is really not possible.

  • 1

    I gave an answer because the current accept does not speak the most important things on the subject.

2 answers

8


Creating an operator is not possible in the language. So the operator ~ will only exist if the designers and I doubt that this will ever happen.

Some existing operators, not all, may have their behavior changed in a certain type - not superscripted. The term used is overload.

Anyway the example used is not possible. The two expressions do not make sense. Because in the language the = is the allocation operator (it cannot be overloaded), on his left side (lvalue) cannot use other operators as used.

Although this was a typo and actually the operator there was the == (which can be overloaded), the second example would make no sense in the language. And, of course, the operator ~ there is no.

If you want to overload the operators you can and use in the right place, then I say don’t.

Are you sure you know what you’re doing? Do you know all the implications? Will you do something useful with it? Will it be intuitive for those who will use it? That is, the programmer who will use your operator will understand what is happening there?

Very few types need to have their own operators and they have equivalence in mathematics. Preferably in obvious things. It is not to abuse the overload of operators. It is not to create for anything, it is not to make creative use. There is language that has chosen not to have this precisely to avoid abuse (which I disagree, because anything can be abused).

If you’re really going to do this, a good start is reading the whole tutorial "official" with great attention, read the documentation, the specification and research a lot on the subject.

Understand that the operators are static. Understand that some operators may suggest a behavior that requires a specific code for everything to go well (only an example of this).

Maybe the operator that makes the most sense in some types is the cast implicit or explicit. And this almost nobody thinks. People are not so creative. Even this can be abused. But it is more common for you to need an operator to convert from one type to another than to pretend that a symbol of + do something different, after all this symbol should only be used for addition, preferably numerical. There is already controversy whether it should be used for text, as it is used in language. Even so there are those who prefer to make a type converter method than to use the operator in cases not so clear.

Another operator where it is common to overload is equality, where it has been said that you need to make sure you understand how it works.

Real example of use in a kind that makes sense (extremely simplified form):

using static System.Console;

class Complex {
    private int real;
    private int imaginary;
    public Complex(int i, int j) {
        real = i;
        imaginary = j;
    }
    public override bool Equals(object o) => ((Complex)o).real == this.real && ((Complex)o).imaginary == this.imaginary;
    public override string ToString() => string.Format("{0} + {1}i", real, imaginary);
    public override int GetHashCode() => this.ToString().GetHashCode();
    public static bool operator == (Complex x, Complex y) => x.Equals(y);
    public static bool operator != (Complex x, Complex y) => !x.Equals(y);
    public static Complex operator +(Complex x, Complex y) => new Complex(x.real + y.real, x.imaginary + y.imaginary);
}
public class Program {
    public static void Main() {
        var x = new Complex(10,20);
        WriteLine(x);
        var y = new Complex(10,20);
        WriteLine(y);
        var z = y;
        WriteLine(z);
        if (x == y) WriteLine("z igual y");
        else WriteLine("x diferente y");
        if (y != z) WriteLine("y diferente z"); 
        else WriteLine("y igual z");
    }
}

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

I will reinforce: almost all the ideas that people have to do operator overload should not be made. The best places he could have ever been made in language.

4

I don’t know if it would be possible to create a unique symbol for you, but it is possible to give an "override" on a certain normal operator using a class.

public class TesteOperador
{
    public float valor
    {
        get;
        set;
    }

    public TesteOperador (float valor)
    {
        this.valor = valor;
    }

    //ou retornando um tipo especifico que você queira... int, float
    public static TesteOperador operator + (TesteOperador A, TesteOperador B)
    {
        return new TesteOperador((A.valor * 2) + (B.valor * 2) / (5));
    }
}

https://dotnetfiddle.net/jXrmHR

Browser other questions tagged

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