Docsity

Understanding Value vs. Reference Types: Pass-by-Value vs. Pass-by-Reference, Slides of Computer Science

Partial preview of the text

Download Understanding Value vs. Reference Types: Pass-by-Value vs. Pass-by-Reference and more Slides Computer Science in PDF only on Docsity!

Types and Passing

Arguments

Value Types If a variable is a value type, then that variable

contains the actual data of that type.Normally a value type contains a single pieceof information, such as an integer, a float, adouble, a bool, or a char.

Pass-by-value Consider the method definition:static double MyAbs(double Y){

if(Y>=0) return Y;else

return –Y;

} There is one parameter in the header. It’s name is Y.

To call the function MyAbs, there needs to be one

argument in the call. Z = MyAbs(Q);When this call is made, the

value

of Q is copied into

the value of Y, the parameter in the function. So, ineffect there are two variables, one in the callingprogram, and the other in MyAbs that contain thesame information.

Q is the argument in thecall.

static void Mystery(string Z){

do something with Z }

In the Main method consider:string Y;Y = “The moon is made of green cheese”;At this point Y contains an address, and that is

the address where the string is stored. Notethat the string is read only.

In the previous example, a reference type was

passed. It’s address was passed by value;hence, the string itself was passed byreference. The string still resides in only oneplace in memory. Its address is stored inboth Z and Y.

Remark about pass-by-value When a variable is passed by value to a

method parameter, changes to thatparameter inside the method, leave thecorresponding variable in the calling programunchanged.

Questions: 1.

What do you do if you want changes to aparameter in the method to result inchanges to the corresponding argument?

What do you do if you want a method tohave access to an argument’s data, but youdon’t want to pass the entire set of data?

static void MySwap(ref int A, ref int B)

int Temp = A;A = B;B = Temp;

} By placing the key word ref in front of the variable

declarations in the header, A and B will now“reference” the corresponding arguments in a call tothis function.

Built-in value and referencetypes Value Types

Integral: sbyte, byte char, short, ushort,intuint,long, and ulong.Floating: float and double.Others: decimal and bool Reference Types

string and object

Summary of types Look at the table in Figure 6.7 on page 196.