Skip to content

Instantly share code, notes, and snippets.

@mickvangelderen
Last active June 21, 2017 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickvangelderen/08414c061c8c06211fb836931370535e to your computer and use it in GitHub Desktop.
Save mickvangelderen/08414c061c8c06211fb836931370535e to your computer and use it in GitHub Desktop.
// Consider the following calls:
// PrintAngle((Radians) 0.10, "radians");
// PrintAngle((Degrees) 30, "degrees");
// Obviously no conversion are required, but without the IAngularUnit
// interface, we would have to provide copies of this method for each
// Unit manually.
public static void PrintAngle<TAngularUnit>(TAngularUnit angle, string unit) where TAngularUnit : IAngularUnit {
switch (unit) {
case "radians": System.Console.WriteLine("{0:F2} rad", (float) angle.ToRadians); break;
case "degrees": System.Console.WriteLine("{0:F2} deg", (float) angle.ToDegrees); break;
case "revolutions": System.Console.WriteLine("{0:F2} rev", (float) angle.ToRevolutions); break;
}
}
// Calling PrintAngleTakingRadians((Degrees) 30, "degrees")
// will perform two unnecessary conversions: 1) from Degrees to Radians when calling
// and 2) from Radians to Degrees in the switch statement. To solve it without the
// interface, we would have to overload the function taking each possible unit.
public static void PrintAngleTakingRadians(Radians angle, string unit) {
switch (unit) {
case "radians": System.Console.WriteLine("{0:F2} rad", (float) angle); break;
case "degrees": System.Console.WriteLine("{0:F2} deg", (float) (Degrees) angle); break;
case "revolutions": System.Console.WriteLine("{0:F2} rev", (float) (Revolutions) angle); break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment