3 public class Fraction
{
5 public Fraction(int numerator
, int denominator
) {
6 Console
.WriteLine("In Fraction Constructor(int, int)");
7 this.numerator
= numerator
;
8 this.denominator
= denominator
;
11 public Fraction(int wholeNumber
) {
12 Console
.WriteLine("In Fraction Constructor(int)");
13 numerator
= wholeNumber
;
17 // this function is not recognised by mcs further down
18 public static implicit operator Fraction(int theInt
) {
19 Console
.WriteLine("In implicit conversion to Fraction");
20 return new Fraction(theInt
);
23 public static explicit operator int(Fraction theFraction
) {
24 Console
.WriteLine("In explicit conversion to int");
25 return theFraction
.numerator
/
26 theFraction
.denominator
;
29 public static bool operator==(Fraction lhs
, Fraction rhs
) {
30 Console
.WriteLine("In operator ==");
31 if (lhs
.denominator
== rhs
.denominator
&&
32 lhs
.numerator
== rhs
.numerator
) {
35 // code here to handle unlike fraction
39 public static bool operator!=(Fraction lhs
, Fraction rhs
) {
40 Console
.WriteLine("In operator !=");
44 public override bool Equals(object o
) {
45 Console
.WriteLine("In method Equals");
46 if (! (o
is Fraction
)) {
49 return this == (Fraction
) o
;
52 public static Fraction
operator+(Fraction lhs
, Fraction rhs
) {
53 Console
.WriteLine("In operator +");
54 if (lhs
.denominator
== rhs
.denominator
) {
55 return new Fraction(lhs
.numerator
+ rhs
.numerator
,
59 // simplistic solution for unlike fractions
60 // 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
61 int firstProduct
= lhs
.numerator
* rhs
.denominator
;
62 int secondProduct
= lhs
.denominator
* rhs
.numerator
;
64 firstProduct
+ secondProduct
,
65 lhs
.denominator
* rhs
.denominator
);
68 public override string ToString() {
69 String s
= numerator
.ToString() + "/" +
70 denominator
.ToString();
74 private int numerator
;
75 private int denominator
;
79 public static int Main() {
81 Fraction f1
= new Fraction(3,4);
82 Console
.WriteLine("f1: {0}", f1
.ToString());
84 Fraction f2
= new Fraction(2,4);
85 Console
.WriteLine("f2: {0}", f2
.ToString());
87 Fraction f3
= f1
+ f2
;
88 Console
.WriteLine("f1 + f2 = f3: {0}", f3
.ToString());
91 Console
.WriteLine("f3 + 5 = f4: {0}", f4
.ToString());
93 Fraction f5
= new Fraction(2, 4);
95 Console
.WriteLine("f5: {0} == f2: {1}", f5
.ToString(), f2
.ToString());