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

Optional parameters in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Optional Parameters in C#
📖 Scenario: You are creating a simple greeting program that can say hello to a person. Sometimes you want to include their title, and sometimes you just want to say hello with their name only.
🎯 Goal: Build a method called Greet that uses optional parameters to greet a person with or without their title.
📋 What You'll Learn
Create a method called Greet with two parameters: string name and an optional string title.
The optional parameter title should have a default value of an empty string.
If title is provided, the greeting should include it before the name.
If title is not provided, the greeting should just use the name.
Call the Greet method twice: once with both name and title, and once with only name.
Print the greetings to the console.
💡 Why This Matters
🌍 Real World
Optional parameters help make your methods flexible and easier to use when some information is not always needed.
💼 Career
Understanding optional parameters is important for writing clean, maintainable code in many C# applications, including web, desktop, and mobile development.
Progress0 / 4 steps
1
Create the Greet method with parameters
Write a method called Greet that takes two parameters: string name and string title. For now, do not make title optional. The method should return a string that says "Hello, " followed by the title and name separated by a space.
C Sharp (C#)
Need a hint?

Define a method with two parameters and return the greeting string combining them.

2
Make the title parameter optional
Modify the Greet method so that the title parameter is optional with a default value of an empty string "".
C Sharp (C#)
Need a hint?

Add = "" after the title parameter to make it optional.

3
Add logic to handle empty title
Change the Greet method so that if title is an empty string, it returns "Hello, " followed by just the name. Otherwise, it returns "Hello, " followed by the title and name separated by a space.
C Sharp (C#)
Need a hint?

Use an if statement to check if title is empty and return the correct greeting.

4
Call Greet method and print greetings
In the Main method, call Greet with name as "Alice" and title as "Dr.". Then call Greet with only name as "Bob". Print both returned greetings using Console.WriteLine.
C Sharp (C#)
Need a hint?

Call Greet with both parameters and with only the name. Use Console.WriteLine to print the results.