03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

84 ❘ CHAPTER 4 Data Types, Variables, and Constants<br />

If you run the code now, the following text appears in the Console window.<br />

DoubleIt: 20<br />

DoDouble: 20<br />

This time the DoubleIt method doubled its parameter, and the change was reflected in the value<br />

argument in the calling code.<br />

For Output<br />

The final way you can pass a value into a method uses the out keyword. This keyword means the<br />

parameter is intended to be an output parameter. The argument is passed into the method by reference<br />

so the method can set its value. The method does not assume the value has been initialized before it is<br />

passed into the method, and the method assigns a value to the parameter before it returns.<br />

When Should You Pass for Output<br />

You should pass parameters for output whenever you want a method to initialize a<br />

parameter but the method doesn’t need to use the parameter’s initial value.<br />

For example, suppose a method fetches data about a particular model of car and<br />

uses output parameters to return information about the model such list price, miles<br />

per gallon, horsepower, and number of cup holders. In that case, the method initializes<br />

those values before it returns but doesn’t use any values that those parameters<br />

might have on input, so the parameters should be declared for output.<br />

If you have the choice between declaring a parameter by reference or for output,<br />

declare it for output because that is more restrictive and may help you catch bugs.<br />

When you declare a parameter for output, Visual Studio does not require the calling<br />

code to initialize the parameter passed into the method. It also flags any code that<br />

uses the parameter’s input value as an error because marking the parameter for output<br />

indicates that its input value is not needed.<br />

As is the case for the ref keyword, if you add the out keyword to a parameter declaration, you must<br />

also include it with the argument. The following code shows the previous example modified to use<br />

the out keyword.<br />

private void DoubleTest()<br />

{<br />

int value;<br />

DoubleIt(out value);<br />

Console.WriteLine("DoubleTest: " + value.ToString());<br />

}<br />

private void DoubleIt(out int number)<br />

{<br />

number = 50;<br />

Console.WriteLine("DoubleIt: " + number.ToString());<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!