Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Extending struct Double


Here is the class DoubleExtensions which defines the methods Square and Sqrt:

using System;

public static class DoubleExtensions{

  public static double Square(this Double d){
    return d * d;
  }

  public static double Sqrt(this Double d){
    return Math.Sqrt(d);
  }

}

The extension methods can be called in the following ways in the method DistanceTo in class PointExtensions:

using System;

public static class PointExtensions{

  public static double DistanceTo(this Point p1, Point p2){

    return ((p1.X - p2.X).Square() + (p1.Y - p2.Y).Square()).Sqrt();

  }

}

Do you like the idea of calling numeric functions, such as Square as n.Square() instead of Square(n)?