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

Optional parameters in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What are optional parameters in C#?
Optional parameters are method parameters that have a default value. When calling the method, you can skip these parameters, and the default value will be used.
Click to reveal answer
beginner
How do you declare an optional parameter in C#?
You declare an optional parameter by assigning it a default value in the method signature, for example:
void Greet(string name = "Guest")
Click to reveal answer
intermediate
Can optional parameters be placed anywhere in the parameter list?
No. Optional parameters must come after all required parameters in the method signature.
Click to reveal answer
beginner
What happens if you call a method without providing an optional parameter?
The method uses the default value specified for that optional parameter.
Click to reveal answer
beginner
Example: What is the output of this code?<br>
void PrintMessage(string message = "Hello") { Console.WriteLine(message); }<br>PrintMessage();
The output is:<br>
Hello
<br>Because the method was called without an argument, so the default value "Hello" is used.
Click to reveal answer
How do you specify an optional parameter in C#?
ABy placing the parameter inside square brackets
BBy assigning a default value in the method signature
CBy marking the parameter with the keyword 'optional'
DBy declaring the parameter as 'null'
Where must optional parameters be placed in the parameter list?
AAfter all required parameters
BAnywhere in the list
COnly as the first parameter
DBefore required parameters
What happens if you call a method without providing an optional parameter?
AThe default value of the optional parameter is used
BThe method throws an error
CThe parameter is set to null
DThe method ignores the parameter
Which of these is a valid method declaration with an optional parameter?
Avoid Foo(int x = 5, int y = 10, int z)
Bvoid Foo(int x = 5, int y)
Cvoid Foo(int x, int y)
Dvoid Foo(int x, int y = 10)
Can optional parameters be used with named arguments?
ANo, named arguments cannot be used with optional parameters
BOnly if all parameters are optional
CYes, you can skip optional parameters by naming others
DOnly in static methods
Explain what optional parameters are and how to use them in C# methods.
Think about how you can make some method inputs not required.
You got /4 concepts.
    Describe the rules about the position of optional parameters in a method's parameter list.
    Consider what happens if you put an optional parameter before a required one.
    You got /3 concepts.