03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

632 ❘ APPENDIX A Solutions to Exercises<br />

copy of x’s value. The pre-increment operator can work only on items such as variables that it<br />

can increment, so it fails.<br />

If you enter ++x++ in the code, Visual Studio flags it with this error:<br />

The operand of an increment or decrement operator must be a variable, property or indexer<br />

2. The following code uses if statements instead of : and .<br />

if (amount < 0) amountLabel.ForeColor = Color.Red;<br />

else amountLabel.ForeColor = Color.Blue;<br />

Customer orderedBy;<br />

if (customer != null) orderedBy = customer;<br />

else orderedBy = new Customer();<br />

The following code shows a slightly more concise way to set orderedBy.<br />

Customer orderedBy = customer;<br />

if (customer == null) orderedBy = new Customer();<br />

3. The code starts by using System.Object.<strong>Reference</strong>Equals to see if the operands refer<br />

to the same object. If they are both null, then they refer to the same null object, so the<br />

method returns true.<br />

4. The following code shows a subtraction operator for the Complex class.<br />

public static Complex operator -(Complex operand1, Complex operand2)<br />

{<br />

return new Complex()<br />

{<br />

Re = operand1.Re - operand2.Re,<br />

Im = operand1.Im - operand2.Im<br />

};<br />

}<br />

Alternatively, because the class already defines addition and unary negation, you could use<br />

the following simpler subtraction operator.<br />

public static Complex operator -(Complex operand1, Complex operand2)<br />

{<br />

return operand1 + (-operand2);<br />

}<br />

5. The following code shows a simple Fraction class with * and / operators.<br />

public class Fraction<br />

{<br />

public double Numerator = 0;<br />

public double Denominator = 0;<br />

public static Fraction operator *(Fraction operand1, Fraction operand2)<br />

{<br />

return new Fraction()<br />

{<br />

Numerator = operand1.Numerator * operand2.Numerator,<br />

Denominator = operand1.Denominator * operand2.Denominator<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!