Overloading Equals and Not Equals - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Overloading Equals and Not Equals

Demo Code

using System;/*from w  w w. j  a  v a  2s . c  o  m*/
using System.Text;
public class Salary
{
   private int AMT;
   public Salary() { this.amount = 0; }
   public Salary(int val) { this.amount = val; }
   public int amount
   {
      get{ return this.AMT; }
      set{ this.AMT = value; }
   }
   public override bool Equals(object val)
   {
      bool retval;
      if( ((Salary)val).amount == this.amount )
         retval = true;
      else
         retval = false;
         return retval;
      }
      public override int GetHashCode()
      {
         return this.ToString().GetHashCode();
      }
      static public bool operator == ( Salary first, Salary second )
      {
         bool retval;
         retval = first.Equals(second);
         return retval;
      }
      static public bool operator != ( Salary first, Salary second )
      {
         bool retval;
         retval = !(first.Equals(second));
         return retval;
      }
      public override string ToString()
      {
         return( this.amount.ToString() );
      }
   }
   public class myAppClass
   {
      public static void Main(String[] args)
      {
         string tmpstring;
         Salary mySalary   = new Salary(24000);
         Salary yourSalary = new Salary(24000);
         Salary PresSalary = new Salary(200000);
         Console.WriteLine("Original values: {0}, {1}, {2}",
         mySalary, yourSalary, PresSalary);
         if (mySalary == yourSalary)
            tmpstring = "equals";
         else
            tmpstring = "does not equal";
            Console.WriteLine("\nMy salary {0} your salary", tmpstring);
            if (mySalary == PresSalary)
               tmpstring = "equals";
            else
               tmpstring = "does not equal";
               Console.WriteLine("\nMy salary {0} a president\'s salary",
               tmpstring);
            }
}

Result


Related Tutorials