C# में कुछ ऑपरेटर्स को ओवरलोड किया जा सकता है, कुछ को नहीं।
ओवरलोड किए जा सकने वाले ऑपरेटर्स
| श्रेणी | ऑपरेटर्स | विवरण |
| यूनरी | + - ! ~ ++ -- | एक ऑपरेंड लेते हैं |
| बाइनरी अंकगणितीय | + - * / % | दो ऑपरेंड लेते हैं |
| तुलनात्मक | == != < > <= >= | पेयर में ओवरलोड करना आवश्यक (== के साथ !=, < के साथ >) |
ओवरलोड नहीं किए जा सकने वाले ऑपरेटर्स
| श्रेणी | ऑपरेटर्स | कारण |
| कंडीशनल लॉजिकल | && || | शॉर्ट-सर्किट मूल्यांकन के कारण सीधे ओवरलोड नहीं; & | ओवरलोड करके अप्रत्यक्ष रूप से |
| असाइनमेंट | += -= *= /= %= | कंपाउंड असाइनमेंट स्वचालित रूप से बाइनरी ऑपरेटर से जुड़े होते हैं |
| अन्य | = . ?. : ?? new is sizeof typeof | भाषा सिंटैक्स का मूल भाग |
ओवरलोडिंग उदाहरण
public struct Complex {
public double Real, Imaginary;
public Complex(double r, double i) { Real = r; Imaginary = i; }
// बाइनरी + ओवरलोड
public static Complex operator +(Complex a, Complex b) {
return new Complex(a.Real + b.Real, a.Imaginary + b.Imaginary);
}
// यूनरी - ओवरलोड
public static Complex operator -(Complex a) {
return new Complex(-a.Real, -a.Imaginary);
}
// == और != पेयर में ओवरलोड
public static bool operator ==(Complex a, Complex b) {
return a.Real == b.Real && a.Imaginary == b.Imaginary;
}
public static bool operator !=(Complex a, Complex b) {
return !(a == b);
}
// Equals/GetHashCode भी ओवरराइड करें
public override bool Equals(object obj) => obj is Complex c && this == c;
public override int GetHashCode() => HashCode.Combine(Real, Imaginary);
}
नियम:
== और != एक साथ ओवरलोड करने चाहिए
< और > एक साथ, <= और >= एक साथ
- ऑपरेटर्स
public static होने चाहिए
- कम से कम एक पैरामीटर डिक्लेयरिंग टाइप का होना चाहिए