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.

68 ❘ ChaPTer 3 Objects And types<br />

Each parameter consists of the name of the type of the parameter, <strong>and</strong> the name by which it can be<br />

referenced in the body of the method. Also, if the method returns a value, a return statement must be used<br />

with the return value to indicate each exit point. For example:<br />

public bool IsSquare(Rectangle rect)<br />

{<br />

return (rect.Height == rect.Width);<br />

}<br />

This code uses one of the .<strong>NET</strong> base classes, System.Drawing.Rectangle, which represents a rectangle.<br />

If the method doesn’t return anything, you specify a return type of void because you can’t omit the return<br />

type altogether, <strong>and</strong> if it takes no arguments, you still need to include an empty set of parentheses after the<br />

method name. In this case, including a return statement is optional — the method returns automatically<br />

when the closing curly brace is reached. You should note that a method can contain as many return<br />

statements as required:<br />

public bool IsPositive(int value)<br />

{<br />

if (value < 0)<br />

return false;<br />

return true;<br />

}<br />

Invoking Methods<br />

The following example, MathTest, illustrates the syntax for definition <strong>and</strong> instantiation of classes, <strong>and</strong><br />

definition <strong>and</strong> invocation of methods. Besides the class that contains the Main() method, it defines a class<br />

named MathTest, which contains a couple of methods <strong>and</strong> a field.<br />

using System;<br />

namespace Wrox<br />

{<br />

class MainEntryPoint<br />

{<br />

static void Main()<br />

{<br />

// Try calling some static functions.<br />

Console.WriteLine("Pi is " + MathTest.GetPi());<br />

int x = MathTest.GetSquareOf(5);<br />

Console.WriteLine("Square of 5 is " + x);<br />

// Instantiate at MathTest object<br />

MathTest math = new MathTest(); // this is <strong>C#</strong>'s way of<br />

// instantiating a reference type<br />

}<br />

}<br />

// Call nonstatic methods<br />

math.value = 30;<br />

Console.WriteLine(<br />

"Value field of math variable contains " + math.value);<br />

Console.WriteLine("Square of 30 is " + math.GetSquare());<br />

// Define a class named MathTest on which we will call a method<br />

class MathTest<br />

{<br />

public int value;<br />

public int GetSquare()<br />

{<br />

return value*value;<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!