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.

72 ❘ ChaPTer 3 Objects And types<br />

Method Overloading<br />

<strong>C#</strong> supports method overloading — several versions of the method that have different signatures (that is,<br />

the same name, but a different number of parameters <strong>and</strong>/or different parameter data types). To overload<br />

methods, you simply declare the methods with the same name but different numbers or types of parameters:<br />

class ResultDisplayer<br />

{<br />

void DisplayResult(string result)<br />

{<br />

// implementation<br />

}<br />

}<br />

void DisplayResult(int result)<br />

{<br />

// implementation<br />

}<br />

If optional parameters won’t work for you, then you need to use method overloading to achieve the same effect:<br />

class MyClass<br />

{<br />

int DoSomething(int x) // want 2nd parameter with default value 10<br />

{<br />

DoSomething(x, 10);<br />

}<br />

}<br />

int DoSomething(int x, int y)<br />

{<br />

// implementation<br />

}<br />

As in any language, method overloading carries with it the potential for subtle runtime bugs if the wrong<br />

overload is called. Chapter 4 discusses how to code defensively against these problems. For now, you should<br />

know that <strong>C#</strong> does place some minimum restrictions on the parameters of overloaded methods:<br />

➤<br />

➤<br />

Properties<br />

It is not sufficient for two methods to differ only in their return type.<br />

It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref<br />

or out.<br />

The idea of a property is that it is a method or pair of methods that is dressed to look like a field. A good<br />

example of this is the Height property of a Windows Form. Suppose that you have the following code:<br />

// mainForm is of type System.Windows.Forms<br />

mainForm.Height = 400;<br />

On executing this code, the height of the window will be set to 400, <strong>and</strong> you will see the window resize<br />

on the screen. Syntactically, this code looks like you’re setting a field, but in fact you are calling a property<br />

accessor that contains code to resize the form.<br />

To define a property in <strong>C#</strong>, you use the following syntax:<br />

public string SomeProperty<br />

{<br />

get<br />

{<br />

return "This is the property value.";<br />

}<br />

set<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!