Optional Parameters का उपयोग
एक optional parameter का एक built-in backup जवाब होता है, जैसे एक burger जिसमें cheese होता है जब तक आप मना न करें। Callers इसे छोड़ सकते हैं और default उपयोग होता है।
In this page:
Syntax
static void MethodName(type required, type optional = defaultValue)
{
// body
}
MethodName(a); // uses the default
MethodName(a, b); // overrides it
Optional Parameters
कोई parameter method declaration में एक default value देकर optional बन जाता है, callers को इसे पूरी तरह छोड़ने देते हुए। Optional parameters को सभी required parameters के बाद आना चाहिए।
Named arguments आपको पहले वाले optional parameters को skip करने और बाद वाले को सीधे सेट करने देते हैं।
Warning:
Optional parameter defaults call site के compile time पर बेक हो जाते हैं, method के नहीं — सावधान रहें अगर आप बाद में callers को recompile किए बिना एक default बदलते हैं।
उदाहरण: Optional Parameters
using System;
class Program
{
static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
static void Main(string[] args)
{
Greet("Priya");
Greet("Priya", "Welcome");
Greet(name: "Lee", greeting: "Hi");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी required parameter से पहले एक optional parameter रखना, जो एक compile error है।
- एक non-constant default value उपयोग करना, जो एक compile-time constant होना चाहिए।
- किसी library में एक default value बदलना और पुराने callers के इसे बिना recompile किए पाने की उम्मीद करना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: