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 6Click 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 123Click to reveal answer
Which keyword requires the variable to be initialized before passing it to a method?
✗ Incorrect
The
ref keyword requires the variable to be initialized before passing it to the method.What must a method do with an
out parameter before it returns?✗ Incorrect
A method must assign a value to an
out parameter before returning.Which keyword allows a method to modify the original variable passed in?
✗ Incorrect
ref allows the method to modify the original variable.Can you pass an uninitialized variable with
ref keyword?✗ Incorrect
Variables passed with
ref must be initialized before the call.Which keyword is commonly used to return multiple values from a method?
✗ Incorrect
out parameters are often used to return multiple values from a method.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.