Docsity

Understanding Pass by Reference, const, readonly and struct in C#, Slides of Information Security and Markup Languages

Toggle sidebar
bg1
Pass by Reference,
const, readonly, struct
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Understanding Pass by Reference, const, readonly and struct in C# and more Slides Information Security and Markup Languages in PDF only on Docsity!

Pass by Reference,

const, readonly, struct

Pass by Reference Parameters

 The parameters we have seen so far are value parameters

 their arguments are passed by value

 if you change the value of a parameter in function, corresponding

argument does NOT change in the caller function

 Let’s see an example: PassByRef.cs.

Underlying Mechanisms

• For value parameters, the arguments’ values are

copied into parameters

  • arguments and parameters have different memory locations double Average (int a, int b) Average(num1, num2) 10 15 10 15 copy value (^) copy value main function

Underlying Mechanisms

 For reference parameters, the parameter and the

argument share the same memory location

 parameter is an alias of argument double average (ref int a, int b) average(ref num1, num2) 10 15 15 refers to the same memory location copy value main function

Example: Swap

void swap(ref int a, ref int b) { int temp; temp = a; a = b; b = temp; }

  • How do we use this in main? int a=5, b=8; swap(ref a, ref b); // a becomes 8, b becomes 5 swap(ref a, ref 5); // syntax error, arguments must be variables

Passing Arrays as Parameters

 To pass an array argument to a method, specify the name of the

array without any brackets. For a method to receive an array

reference through a method call, the method’s parameter list must

specify an array parameter.

 When an argument to a method is an entire array or an individual

array element of a reference type, the called method receives a

copy of the reference.

 When an argument to a method is an individual array element of a

value type, the called method receives a copy of the element’s

value.

 To pass an individual array element to a method, use the indexed

name of the array as an argument in the method call.

 Example: ArrayReferenceTest.cs

const

  • Cannot use const with reference types.
  • Exception: string public const string CLASSNAME = “IT 528”;

readonly

 const is set at compile time

 readonly is set at runtime

 readonly can be used for reference types as

well

 Constructor can set readonly fields but not

any other methods

public class GradeBook { private readonly string courseName = “”; public GradeBook(string name) { courseName = name; } }