J

#### JohnGoogle

For my own educational process I am implementing a Fraction class

described in the VSJ magazine to help me understand Visual C# operator

overloading. I'm a relative newbie.

At the moment my basic code is:

using System;

using System.Collections.Generic;

using System.Text;

namespace XYZ.Common

{

//

// This class is to demonstrate how to overload operators such as

+, -, ++.

//

public class Fraction

{

private Int32 numerator;

private Int32 denominator;

// Constructors

// 'Whole numbers'

public Fraction(Int32 numerator)

{

this.numerator = numerator;

this.denominator = 1;

}

// 'True fractions'

public Fraction(Int32 numerator, Int32 denominator)

{

this.numerator = numerator;

this.denominator = denominator;

}

// Implementation of the + operator

public static Fraction operator+(Fraction lhs, Fraction rhs)

{

if (lhs.denominator == rhs.denominator)

{

return new Fraction(lhs.numerator + rhs.numerator,

lhs.denominator);

}

else

{

Int32 denominator = lhs.denominator * rhs.denominator;

Int32 firstProduct = (denominator / lhs.denominator) *

lhs.numerator;

Int32 secondProduct = (denominator / rhs.denominator) *

rhs.numerator;

return new Fraction(firstProduct + secondProduct,

denominator);

}

}

// Implementation of the ++ operator - VERSION 1

public static Fraction operator ++(Fraction f)

{

f.numerator++;

return f;

}

// Implementation of the ++ operator - VERSION 2

public static Fraction operator ++(Fraction f)

{

return new Fraction(f.numerator + 1, f.denominator);

}

public override string ToString()

{

return numerator.ToString() + "/" + denominator.ToString();

}

}

}

My problem is that both versions of the operator ++ method compile and

return the correct result.

Version 1 simply returns the original object after amending it. Version

2 creates and returns a totally new object.

Which is the correct version to use with regard to memory allocation

etc?

Thanks for any help.