Darf Zon
Darf Zon

Reputation: 6378

Is possible to add operator a class?

look the UML image. I've got a generic class called BinaryProblem, this one receives two values of T value, int long, decimal. But I decided add a new one, Fraction class.

enter image description here

Suppose that I have a method called Add, Substract, Multiplicate and Division. I'd like to do something like this.

var a = new Fraction(1 / 2);
var b = new Fraction(3 / 4);
var c = a + b;  // Fraction { Numerator = 5, Denominator = 4 } 

I know that can only put an condition, if (x.GetType() == ...) but, I'm sure later I'd add another types, and avoid to repeat some code.

I almost forget it, is possible to add numbers where the type is generic?

Upvotes: 1

Views: 2299

Answers (1)

JaredPar
JaredPar

Reputation: 755457

It sounds like you're trying to add the operator + to the Fraction type. If so try the following

class Fraction { 
  public static Fraction operator+(Fraction left, Fraction right) {
    return left.Add(right);
  }

  public static Fraction operator+(Fraction left, int right) {
    var right = new Fraction(right);
    return left.Add(right);
  }
}

Upvotes: 4

Related Questions