O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12: Operator Overloading

Quiz

Solution to Question 12–1.

The process of writing methods for your class that allow clients of your class to interact with your class using standard operators (+, ==).

Solution to Question 12–2.

Static methods.

Solution to Question 12–3.

Call to:

public static Fraction operator+(f2, f1)
Solution to Question 12–4.

Overload the Equals( ) method.

Solution to Question 12–5.

Use implicit conversion when you know the conversion will succeed without the risk of losing information. Use explicit conversion if information might be lost.

Exercises

Solution to Exercise 12-1.

Create a class Invoice, that has a string property vendor and a double property amount. Overload the addition operator so that if the vendor properties match, the amount properties of the two invoices are added together in a new invoice. If the vendor properties do not match, the new invoice is blank.

using System; public class Invoice { private string vendor; private double amount; public string Vendor { get { return vendor; } set { vendor = value; } } public double Amount { get { return amount; } set { amount = value; } } // constructor public Invoice(string vendor, double amount) { this.vendor = vendor; this.amount = amount; } // Overloaded operator + takes two invoices. // If the vendors are the same, the two amounts are added. // If not, the operation fails, and a blank invoice is returned. public static Invoice operator +(Invoice lhs, Invoice rhs) { if (lhs.vendor == rhs.vendor) { return new ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required