← Back to C# Course | Chapter 5: Methods | Lesson 5 of 6

Optional Parameters का उपयोग

एक optional parameter का एक built-in backup जवाब होता है, जैसे एक burger जिसमें cheese होता है जब तक आप मना न करें। Callers इसे छोड़ सकते हैं और default उपयोग होता है।

In this page:

  1. Optional Parameters
Syntax
csharp
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

markup
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");
    }
}
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. #}
आम गलतियां
  1. किसी required parameter से पहले एक optional parameter रखना, जो एक compile error है।
  2. एक non-constant default value उपयोग करना, जो एक compile-time constant होना चाहिए।
  3. किसी library में एक default value बदलना और पुराने callers के इसे बिना recompile किए पाने की उम्मीद करना।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.