15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

operator overloading ❘ 171<br />

You also need to override the != operator. The simple way to do this is:<br />

public static bool operator != (Vector lhs, Vector rhs)<br />

{<br />

return ! (lhs == rhs);<br />

}<br />

As usual, you should quickly check that your override works with some test code. This time you’ll define<br />

three Vector objects <strong>and</strong> compare them:<br />

static void Main()<br />

{<br />

Vector vect1, vect2, vect3;<br />

vect1 = new Vector(3.0, 3.0, -10.0);<br />

vect2 = new Vector(3.0, 3.0, -10.0);<br />

vect3 = new Vector(2.0, 3.0, 6.0);<br />

Console.WriteLine("vect1==vect2 returns " + (vect1==vect2));<br />

Console.WriteLine("vect1==vect3 returns " + (vect1==vect3));<br />

Console.WriteLine("vect2==vect3 returns " + (vect2==vect3));<br />

Console.WriteLine();<br />

}<br />

Console.WriteLine("vect1!=vect2 returns " + (vect1!=vect2));<br />

Console.WriteLine("vect1!=vect3 returns " + (vect1!=vect3));<br />

Console.WriteLine("vect2!=vect3 returns " + (vect2!=vect3));<br />

code snippet Vectors3.cs<br />

Compiling this code (the Vectors3.cs sample in the code download) generates the following compiler<br />

warning because you haven’t overridden Equals() for your Vector. For our purposes here, that does not<br />

matter, so we will ignore it.<br />

Microsoft (R) Visual <strong>C#</strong> 2010 Compiler version 4.0.21006.1<br />

for Microsoft (R) .<strong>NET</strong> Framework version 4.0<br />

Copyright (C) Microsoft Corporation. All rights reserved.<br />

Vectors3.cs(5,11): warning CS0660: ‘Wrox.ProCSharp.OOCSharp.Vector’ defines<br />

operator == or operator != but does not override Object.Equals(object o)<br />

Vectors3.cs(5,11): warning CS0661: ‘Wrox.ProCSharp.OOCSharp.Vector’ defines<br />

operator == or operator != but does not override Object.GetHashCode()<br />

Running the example produces these results at the comm<strong>and</strong> line:<br />

Vectors3<br />

vect1==vect2 returns True<br />

vect1==vect3 returns False<br />

vect2==vect3 returns False<br />

vect1!=vect2 returns False<br />

vect1!=vect3 returns True<br />

vect2!=vect3 returns True<br />

Which operators Can you overload<br />

It is not possible to overload all the available operators. The operators that you can overload are listed in the<br />

following table.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!