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

ref और out Parameters

ref और out किसी method को आपके original variable के साथ सीधे काम करने देते हैं बजाय एक copy के, जैसे अपनी असली notebook उधार देना बजाय एक photocopy के। out के साथ, method को आपके लिए जवाब भरना ही चाहिए।

In this page:

  1. ref and out Parameters
Syntax
csharp
static void MethodName(ref type parameter)   // read and modify caller's variable
{
}

static bool TryMethod(type input, out type result)   // must assign result
{
    result = value;
    return true;
}

MethodName(ref variable);
TryMethod(input, out type result);

ref and out Parameters

ref किसी variable को reference से पास करता है ताकि method caller की original value पढ़ और modify कर सके; variable पहले से initialized होना चाहिए।

out भी reference से पास करता है लेकिन उन methods के लिए है जो एक value assign करते हैं जो method को नहीं मिली थी, जैसे TryParse। दोनों को declaration और call site दोनों पर ref/out keyword चाहिए।

Warning: एक out parameter को method के return होने से पहले इसके अंदर assign होना चाहिए, नहीं तो compiler code को reject कर देता है।

उदाहरण: ref and out Parameters

markup
using System;

class Program
{
    static void Double(ref int x)
    {
        x = x * 2;
    }

    static bool TryDivide(int a, int b, out int result)
    {
        if (b == 0)
        {
            result = 0;
            return false;
        }
        result = a / b;
        return true;
    }

    static void Main(string[] args)
    {
        int n = 5;
        Double(ref n);
        Console.WriteLine(n);

        if (TryDivide(10, 2, out int quotient))
            Console.WriteLine(quotient);
    }
}
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. call site पर ref या out keyword भूल जाना, जो एक compile error है।
  2. ref को एक uninitialized variable पास करना, जबकि ref को एक initialized variable चाहिए और out को नहीं।
  3. method के हर code path में एक out parameter को assign न करना, जो एक compile error है।
चैप्टर सारांश
  • Methods parameters और return types के साथ reusable code को group करते हैं।
  • Method overloading और optional parameters methods को flexible बनाते हैं।
  • ref और out parameters values को reference से पास करते हैं या अतिरिक्त results return करते हैं।
🔒

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.