15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

86 ❘ ChaPTer 3 Objects And types<br />

{<br />

static void Main(string[] args)<br />

{<br />

Money cash1 = new Money();<br />

cash1.Amount = 40M;<br />

Console.WriteLine("cash1.ToString() returns: " + cash1.ToString());<br />

Console.ReadLine();<br />

}<br />

}<br />

public class Money<br />

{<br />

private decimal amount;<br />

}<br />

public decimal Amount<br />

{<br />

get<br />

{<br />

return amount;<br />

}<br />

set<br />

{<br />

amount = value;<br />

}<br />

}<br />

public override string ToString()<br />

{<br />

return "$" + Amount.ToString();<br />

}<br />

}<br />

This example is here just to illustrate syntactical features of <strong>C#</strong>. <strong>C#</strong> already has a predefined type<br />

to represent currency amounts, decimal, so in real life, you wouldn’t write a class to duplicate<br />

this functionality unless you wanted to add various other methods to it. And in many cases, due to<br />

formatting requirements, you’d probably use the String.Format() method (which is covered in<br />

Chapter 8) rather than ToString() to display a currency string.<br />

In the Main() method, you first instantiate a Money object. The ToString() method is then called, which<br />

actually executes the override version of the method. Running this code gives the following results:<br />

cash1.ToString() returns: $40<br />

eXTension meThods<br />

There are many ways to extend a class. If you have the source for the class, then inheritance, which is<br />

covered in Chapter 4, is a great way to add functionality to your objects. What if the source code isn’t<br />

available Extension methods can help by allowing you to change a class without requiring the source code<br />

for the class.<br />

Extension methods are static methods that can appear to be part of a class without actually being in the<br />

source code for the class. Let’s say that the Money class from the previous example needs to have a method<br />

AddToAmount(decimal amountToAdd). However, for whatever reason the original source for the assembly<br />

cannot be changed directly. All that you have to do is create a static class <strong>and</strong> add the AddToAmount method<br />

as a static method. Here is what the code would look like:<br />

namespace Wrox<br />

{<br />

public static class MoneyExtension<br />

{<br />

public static void AddToAmount(this Money money, decimal amountToAdd)<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!