ref और out Parameters
ref और out किसी method को आपके original variable के साथ सीधे काम करने देते हैं बजाय एक copy के, जैसे अपनी असली notebook उधार देना बजाय एक photocopy के। out के साथ, method को आपके लिए जवाब भरना ही चाहिए।
In this page:
Syntax
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
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);
}
}
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. #}
आम गलतियां
- call site पर
refयाoutkeyword भूल जाना, जो एक compile error है। refको एक uninitialized variable पास करना, जबकिrefको एक initialized variable चाहिए औरoutको नहीं।- method के हर code path में एक
outparameter को assign न करना, जो एक compile error है।
चैप्टर सारांश
- Methods parameters और return types के साथ reusable code को group करते हैं।
- Method overloading और optional parameters methods को flexible बनाते हैं।
refऔरoutparameters values को reference से पास करते हैं या अतिरिक्त results return करते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: