Equality Operator Overloading C# with Example



Equality Operator Overloading C# with Example

 	using System;

	namespace CSharpClass
	{
		class Time
		{
			byte hour {get; set;}
			byte minute {get; set;}
			
			public Time(){}
			public Time(byte h, byte m)
			{
				this.hour = h;
				this.minute = m;
			}
			
			public override bool Equals(object arg)
			{
				return arg.ToString() == this.ToString();
			}
			
			public override int GetHashCode()
			{
				return this.ToString().GetHashCode();
			}
			
			public static bool operator ==(Time operand1, Time operand2)
			{
				return operand1.Equals(operand2);
			}

			public static bool operator !=(Time operand1, Time operand2)
			{
				return !operand1.Equals(operand2);
			}
		}

		class EqualityOperatorOverloading
		{
			static void Main()
			{
				Time hmt = new Time(12, 10);
				Time sonata = new Time(12, 10);
				Time titan = new Time(10, 20);
				
				Console.WriteLine("HTML == SONATA: {0}", hmt==sonata);
				Console.WriteLine("HTML != SONATA: {0}\n", hmt!=sonata);
				
				Console.WriteLine("HTML == TITAN: {0}", hmt==titan);
				Console.WriteLine("HTML != TITAN: {0}", hmt!=titan);
				
			}
		}
	} 

0 Comment's

Comment Form

Submit Comment