Write a C# function to convert MPH to KPH

Published: Monday 6 November 2023

If you have an application that involves recording the speed, you may need to convert miles-per-hour (MPH) to kilometers-per-hour (KPH).

Here is your chance to write a C# static function that allows you to convert MPH to KPH and vice-versa.

Start off with this code:

public enum SpeedTypeEnum
{
	MPH,
	KPH
}

public static class SpeedHelper
{
	public static decimal ConvertSpeed(decimal speed, SpeedTypeEnum convertToSpeedType)
	{
		throw new NotImplementedException();
	}
}

Inside the SpeedHelper static class, there is a ConvertSpeed function. This expects two parameters:

  • The speed parameter is the speed value we wish to convert.
  • The convertToSpeedUnit parameter is the speed unit we wish to convert to.

1 mile converts to 1.6093 km. Finish the ConvertSpeed function so it returns the value of the speed parameter when converted with the speed unit passed in the convertToSpeedUnit parameter.

For example, if we passed in ConvertSpeed(100, SpeedUnitEnum.KPH), we would expect the return value to be 160.93 (100 * 1.6093).