Home »
.Net »
C# Programs
C# program to overload Equal To (==) and Not Equal To (!=) operators
In this C# program, we are going to learn to overload relational operators like Equal To (==) and Not Equal To (!=). Here is an example with the output.
Submitted by IncludeHelp, on March 18, 2018
Problem statement
Write a C# program to overload Equal To (==) and Not Equal To (!=) operators.
Program to overload Equal To (==) and Not Equal To (!=) operators in C#
If we overload Equal To (==) operator then we must overload Not Equal To (!=) operator. Here, in this program, we will create a sample class with data member X. Assign value using Set() method.
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Sample
{
private int X;
public Sample()
{
X = 0;
}
public void Set(int v)
{
X = v;
}
public static bool operator==(Sample S1, Sample S2)
{
return (S1.X==S2.X);
}
public static bool operator !=(Sample S1, Sample S2)
{
return (S1.X != S2.X);
}
}
class Program
{
static void Main()
{
Sample S1 = new Sample();
Sample S2 = new Sample();
S1.Set(3);
S2.Set(3);
Console.WriteLine(""+(S1==S2));
Console.WriteLine(""+(S1!=S2));
}
}
}
Output
True
False
In this program, we took two object of sample class. And here we overloaded both "Equal To" == and "Not Equal To" != operators. And both overloaded methods are returning Boolean value on the basis of == and != operators.
C# Operator Overloading Programs »