30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

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

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

Chapter 6 Procedures 201<br />

not necessary <strong>to</strong> do so except with type String. Although they technically are reference<br />

types, String arguments cannot be modified directly when passed with keyword ByVal,<br />

due <strong>to</strong> some subtle details of the String data type, which we discuss in Chapter 15,<br />

Strings, Characters and Regular Expressions.<br />

1 ' Fig. 6.12: ByRefTest.vb<br />

2 ' Demonstrates passing by reference.<br />

3<br />

4 Module modByRefTest<br />

5<br />

6 ' squares three values ByVal and ByRef, displays results<br />

7 Sub Main()<br />

8 Dim number1 As Integer = 2<br />

9<br />

10 Console.WriteLine("Passing a value-type argument by value:")<br />

11 Console.WriteLine("Before calling SquareByValue, " & _<br />

12 "number1 is {0}", number1)<br />

13 SquareByValue(number1) ' passes number1 by value<br />

14 Console.WriteLine("After returning from SquareByValue, " & _<br />

15 "number1 is {0}" & vbCrLf, number1)<br />

16<br />

17 Dim number2 As Integer = 2<br />

18<br />

19 Console.WriteLine("Passing a value-type argument" & _<br />

20 " by reference:")<br />

21 Console.WriteLine("Before calling SquareByReference, " & _<br />

22 "number2 is {0}", number2)<br />

23 SquareByReference(number2) ' passes number2 by reference<br />

24 Console.WriteLine("After returning from " & _<br />

25 "SquareByReference, number2 is {0}" & vbCrLf, number2)<br />

26<br />

27 Dim number3 As Integer = 2<br />

28<br />

29 Console.WriteLine("Passing a value-type argument" & _<br />

30 " by reference, but in parentheses:")<br />

31 Console.WriteLine("Before calling SquareByReference " & _<br />

32 "using parentheses, number3 is {0}", number3)<br />

33 SquareByReference((number3)) ' passes number3 by value<br />

34 Console.WriteLine("After returning from " & _<br />

35 "SquareByReference, number3 is {0}", number3)<br />

36<br />

37 End Sub ' Main<br />

38<br />

39 ' squares number by value (note ByVal keyword)<br />

40 Sub SquareByValue(ByVal number As Integer)<br />

41 Console.WriteLine("After entering SquareByValue, " & _<br />

42 "number is {0}", number)<br />

43 number *= number<br />

44 Console.WriteLine("Before exiting SquareByValue, " & _<br />

45 "number is {0}", number)<br />

46 End Sub ' SquareByValue<br />

47<br />

Fig. Fig. 6.12 6.12 ByVal and ByRef used <strong>to</strong> pass value-type arguments (part 1 of 2).

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

Saved successfully!

Ooh no, something went wrong!