Polymorphism

image_pdfimage_print
   
 


using System;

public class MotorVehicle {
    public string make;
    public string model;

    public MotorVehicle(string make, string model) {
        this.make = make;
        this.model = model;
    }

    public virtual void Accelerate() {
        Console.WriteLine(model + " accelerating");
    }

}
public class Product : MotorVehicle {
    public Product(string make, string model) :
        base(make, model) {
    }
    public override void Accelerate() {
        Console.WriteLine("Pushing gas pedal of " + model);
        base.Accelerate();
    }

}
public class Motorcycle : MotorVehicle {
    public Motorcycle(string make, string model) :
        base(make, model) {
        // do nothing
    }

    public override void Accelerate() {
        Console.WriteLine("Twisting throttle of " + model);
        base.Accelerate();
    }

}


class MainClass {

    public static void Main() {
        Product myProduct = new Product("Toyota", "MR2");
        myProduct.Accelerate();

        Motorcycle myMotorcycle =
          new Motorcycle("Harley-Davidson", "V-Rod");
        myMotorcycle.Accelerate();

    }

}

    


Illustrates method overloading

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example5_9.cs illustrates method overloading
*/


// declare the Swapper class
class Swapper
{

  // this Swap() method swaps two int parameters
  public void Swap(ref int x, ref int y)
  {
    int temp = x;
    x = y;
    y = temp;
  }

  // this Swap() method swaps two float parameters
  public void Swap(ref float x, ref float y)
  {
    float temp = x;
    x = y;
    y = temp;
  }

}


public class Example5_9
{

  public static void Main()
  {

    // create a Swapper object
    Swapper mySwapper = new Swapper();

    // declare two int variables
    int intValue1 = 2;
    int intValue2 = 5;
    System.Console.WriteLine("initial intValue1 = " + intValue1 +
      ", intValue2 = " + intValue2);

    // swap the two float variables
    // (uses the Swap() method that accepts int parameters)
    mySwapper.Swap(ref intValue1, ref intValue2);

    // display the final values
    System.Console.WriteLine("final   intValue1 = " + intValue1 +
      ", intValue2 = " + intValue2);

    // declare two float variables
    float floatValue1 = 2f;
    float floatValue2 = 5f;
    System.Console.WriteLine("initial floatValue1 = " + floatValue1 +
      ", floatValue2 = " + floatValue2);

    // swap the two float variables
    // (uses the Swap() method that accepts float parameters)
    mySwapper.Swap(ref floatValue1, ref floatValue2);

    // display the final values
    System.Console.WriteLine("final   floatValue1 = " + floatValue1 +
      ", floatValue2 = " + floatValue2);
    mySwapper.Swap(ref floatValue1, ref floatValue2);

  }

}

           
          


Operator Overloading

image_pdfimage_print
   
 

using System;


public class Rectangle {
    public int width;
    public int height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public override string ToString() {
        return "width = " + width + ", height = " + height;
    }

    public static bool operator ==(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator ==");
        if (lhs.width == rhs.width && lhs.height == rhs.height) {
            return true;
        } else {
            return false;
        }
    }

    public static bool operator !=(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator !=");
        return !(lhs == rhs);
    }

    public override bool Equals(object obj) {
        Console.WriteLine("In Equals()");
        if (!(obj is Rectangle)) {
            return false;
        } else {
            return this == (Rectangle)obj;
        }
    }

    public static Rectangle operator +(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator +");
        return new Rectangle(
          lhs.width + rhs.width, lhs.height + rhs.height);
    }

}
class MainClass {

    public static void Main() {

        Rectangle myRectangle = new Rectangle(1, 4);
        Console.WriteLine("myRectangle: " + myRectangle);
        Rectangle myRectangle2 = new Rectangle(1, 4);
        Console.WriteLine("myRectangle2: " + myRectangle2);

        if (myRectangle == myRectangle2) {
            Console.WriteLine(
              "myRectangle is equal to myRectangle2");
        } else {
            Console.WriteLine(
              "myRectangle is not equal to myRectangle2");
        }

        Rectangle myRectangle3 = myRectangle + myRectangle2;
        Console.WriteLine("myRectangle3: " + myRectangle3);
    }
}

    


Sorting and Searching:Overloading Relational Operators

image_pdfimage_print

   

/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/

// 28 - System.Array and the Collection ClassesSorting and SearchingOverloading Relational Operators
// copyright 2000 Eric Gunnerson
using System;

public class OverloadingRelationalOperators
{
    public static void Main()
    {
        Employee george = new Employee("George", 1);
        Employee fred = new Employee("Fred", 2);
        Employee tom = new Employee("Tom", 4);
        Employee bob = new Employee("Bob", 3);
        
        Console.WriteLine("George < Fred: {0}", george < fred);
        Console.WriteLine("Tom >= Bob: {0}", tom >= bob);
    }
} 
public class Employee: IComparable
{
    public Employee(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
    
    int IComparable.CompareTo(object obj)
    {
        Employee emp2 = (Employee) obj;
        if (this.id > emp2.id)
        return(1);
        if (this.id < emp2.id)
        return(-1);
        else
        return(0);
    }
    public static bool operator <(
    Employee emp1,
    Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) < 0);
    }
    public static bool operator >(
    Employee emp1,
    Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) > 0);
    }
    public static bool operator <=(
    Employee emp1,
    Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) <= 0);
    }
    public static bool operator >=(
    Employee emp1,
    Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) >= 0);
    }
    
    public override string ToString()
    {
        return(name + ":" + id);
    }
    
    string    name;
    int    id;
}

           
          


Operator Overloading:An Example

image_pdfimage_print

   

/*
A Programmer&#039;s Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 25 - Operator OverloadingAn Example
// copyright 2000 Eric Gunnerson
using System;
struct RomanNumeral
{
    public RomanNumeral(int value)
    {
        this.value = value;
    }
    public override string ToString()
    {
        return(value.ToString());
    }
    public static RomanNumeral operator -(RomanNumeral roman)
    {
        return(new RomanNumeral(-roman.value));
    }
    public static RomanNumeral operator +(
    RomanNumeral    roman1,
    RomanNumeral    roman2)
    {
        return(new RomanNumeral(
        roman1.value + roman2.value));
    }
    
    public static RomanNumeral operator ++(
    RomanNumeral    roman)
    {
        return(new RomanNumeral(roman.value + 1));
    }
    int value;
}
public class OperatorOverloadingAnExample
{
    public static void Main()
    {
        RomanNumeral    roman1 = new RomanNumeral(12);
        RomanNumeral    roman2 = new RomanNumeral(125);
        
        Console.WriteLine("Increment: {0}", roman1++);
        Console.WriteLine("Addition: {0}", roman1 + roman2);
    }
}

           
          


Overload != operator

image_pdfimage_print

   

/*
Learning C# 
by Jesse Liberty

Publisher: O&#039;Reilly 
ISBN: 0596003765
*/
 using System;

 class Fraction
 {
     private int numerator;
     private int denominator;

     // create a fraction by passing in the numerator
     // and denominator
     public Fraction(int numerator, int denominator)
     {
         this.numerator=numerator;
         this.denominator=denominator;
     }

     // overload the constructor to create a
     // fraction from a whole number
     public Fraction(int wholeNumber)
     {
         Console.WriteLine("In constructor taking a whole number");
         numerator = wholeNumber;
         denominator = 1;
     }

     // convert ints to Fractions implicitly
     public static implicit operator Fraction(int theInt)
     {
         Console.WriteLine("Implicitly converting int to Fraction");
         return new Fraction(theInt);
     }

     // convert Fractions to ints explicitly
     public static explicit operator int(Fraction theFraction)
     {
         Console.WriteLine("Explicitly converting Fraction to int");
         return theFraction.numerator /
             theFraction.denominator;
     }


     // overloaded operator + takes two fractions
     // and returns their sum
     public static Fraction operator+(Fraction lhs, Fraction rhs)
     {
         // like fractions (shared denominator) can be added
         // by adding thier numerators
         if (lhs.denominator == rhs.denominator)
         {
             return new Fraction(lhs.numerator+rhs.numerator,
                 lhs.denominator);
         }

         // simplistic solution for unlike fractions
         // 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
         // this method does not reduce.
         int firstProduct = lhs.numerator * rhs.denominator;
         int secondProduct = rhs.numerator * lhs.denominator;
         return new Fraction(
             firstProduct + secondProduct,
             lhs.denominator * rhs.denominator
             );
     }

     // test whether two Fractions are equal
     public static bool operator==(Fraction lhs, Fraction rhs)
     {
         if (lhs.denominator == rhs.denominator &amp;&amp;
             lhs.numerator == rhs.numerator)
         {
             return true;
         }
         // code here to handle unlike fractions
         return false;
     }

     // delegates to operator ==
     public static bool operator !=(Fraction lhs, Fraction rhs)
     {
         bool equality = lhs==rhs;
         return !(equality);
     }

     // tests for same types, then delegates
     public override bool Equals(object o)
     {
         if (! (o is Fraction) )
         {
             return false;
         }
         return this == (Fraction) o;
     }

     // return a string representation of the fraction
     public override string ToString()
     {
         String s = numerator.ToString() + "/" +
             denominator.ToString();
         return s;
     }


 }


 public class TesterOverrideThree
 {
     static void Main()
     {
         Fraction f1 = new Fraction(3,4);
         Fraction f2 = new Fraction(2,4);
         Fraction f3 = f1 + f2;

         Console.WriteLine("adding f3 + 5...");
         Fraction f4 = f3 + 5;
         Console.WriteLine("f3 + 5 = f4: {0}", f4.ToString());

         Console.WriteLine("
Assigning f4 to an int...");
         int truncated = (int) f4;
         Console.WriteLine("When you truncate f4 you get {0}",
             truncated);
     }
 }