0
0
C Sharp (C#)programming~5 mins

Ref and out parameters in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the ref keyword in C#?
The ref keyword allows a method to receive a reference to an existing variable, so the method can read and modify the original variable's value.
Click to reveal answer
beginner
How does the out keyword differ from ref in C#?
out parameters must be assigned a value inside the method before returning, and they are used to return multiple values. Unlike ref, the variable passed as out does not need to be initialized before the call.
Click to reveal answer
intermediate
Can you use ref and out parameters without initializing the variable first?
For ref, the variable must be initialized before passing it to the method. For out, the variable does not need to be initialized before the call, but the method must assign it before returning.
Click to reveal answer
beginner
Show a simple example of a method using ref parameter.
Example:<br>
void AddOne(ref int number) {
    number += 1;
}

int x = 5;
AddOne(ref x);
// x is now 6
Click to reveal answer
beginner
Show a simple example of a method using out parameter.
Example:<br>
bool TryParseInt(string s, out int result) {
    return int.TryParse(s, out result);
}

int value;
bool success = TryParseInt("123", out value);
// success is true, value is 123
Click to reveal answer
Which keyword requires the variable to be initialized before passing it to a method?
Aref
Bout
Cin
Dparams
What must a method do with an out parameter before it returns?
AAssign a value to it
BLeave it unassigned
CInitialize it outside the method
DReturn it explicitly
Which keyword allows a method to modify the original variable passed in?
Astatic
Bconst
Cref
Dreadonly
Can you pass an uninitialized variable with ref keyword?
AYes
BNo
COnly if it is a reference type
DOnly if it is a value type
Which keyword is commonly used to return multiple values from a method?
Aref
Bstatic
Cparams
Dout
Explain the difference between ref and out parameters in C#.
Think about when the variable needs to be initialized and how the method uses it.
You got /4 concepts.
    Describe a real-life situation where using out parameters would be helpful.
    Think about methods that try to convert or calculate and need to tell if it worked and give a result.
    You got /3 concepts.