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

Optional parameters in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Optional parameters let you call a method without giving all the values. This makes your code simpler and easier to use.

When a method has many parameters but some usually have the same value.
When you want to give users of your method the choice to skip some arguments.
When you want to avoid writing many method overloads for different parameter sets.
When you want to provide default behavior but allow customization.
When you want to make your API easier to understand and use.
Syntax
C Sharp (C#)
void MethodName(type param1, type param2 = defaultValue) {
    // method body
}

Optional parameters must be placed after all required parameters.

Default values must be constant expressions.

Examples
This method prints a greeting. If no name is given, it uses "Friend".
C Sharp (C#)
void Greet(string name = "Friend") {
    Console.WriteLine($"Hello, {name}!");
}
The second parameter is optional and defaults to 10 if not provided.
C Sharp (C#)
void AddNumbers(int a, int b = 10) {
    Console.WriteLine(a + b);
}
This method optionally converts the message to uppercase before printing.
C Sharp (C#)
void Display(string message, bool uppercase = false) {
    if (uppercase) {
        message = message.ToUpper();
    }
    Console.WriteLine(message);
}
Sample Program

This program shows how to call a method with optional parameters. You can skip some arguments and the defaults will be used.

C Sharp (C#)
using System;

class Program {
    static void ShowInfo(string name, int age = 30, string city = "Unknown") {
        Console.WriteLine($"Name: {name}, Age: {age}, City: {city}");
    }

    static void Main() {
        ShowInfo("Alice");
        ShowInfo("Bob", 25);
        ShowInfo("Charlie", 40, "New York");
    }
}
OutputSuccess
Important Notes

You cannot have a required parameter after an optional one.

Optional parameters help reduce method overloads but use them wisely to keep code clear.

Summary

Optional parameters let you skip arguments by providing default values.

They must come after all required parameters in the method signature.

Use optional parameters to make your methods easier to call and maintain.