Method Overloading क्या है
Method overloading का मतलब है कई methods को एक जैसा नाम लेकिन अलग inputs देना, जैसे draw जो आपके दिए के आधार पर circle या square बना सके। C# आपके पास किए के आधार पर सही वाला चुनता है।
In this page:
Syntax
static int MethodName(int a, int b) { }
static double MethodName(double a, double b) { } // same name, different parameters
static int MethodName(int a, int b, int c) { }
Method Overloading
Overloading कई methods को एक जैसा नाम share करने देता है जब तक उनकी parameter lists type या count में अलग हों। compiler call site पर arguments के आधार पर सही overload चुनता है।
Overloading पूरी तरह compile time पर resolve होता है, runtime values के आधार पर नहीं।
Note:
Overloads को consistently व्यवहार करना चाहिए — एक जैसा नाम, conceptually एक जैसा operation, बस अलग inputs।
उदाहरण: Method Overloading
using System;
class Program
{
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
static int Add(int a, int b, int c) => a + b + c;
static void Main(string[] args)
{
Console.WriteLine(Add(2, 3));
Console.WriteLine(Add(2.5, 3.5));
Console.WriteLine(Add(1, 2, 3));
}
}
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. #}
आम गलतियां
- सिर्फ return type से overload करना, जिसकी अनुमति नहीं है।
- ऐसे overloads बनाना जो किसी call को ambiguous बना दें, जैसे दो ints के साथ call किए
f(int, double)औरf(double, int)। - यह मान लेना कि overload choice runtime पर होती है, जबकि यह argument types से compile time पर चुनी जाती है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: