C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Required input and output for distance conversion
Input: 200 m
321.9 km
500 km
310.7 m
Output: 321.9 km
200 m
310.7 m
500 km
Double: Double stores numbers that are larger and have decimal places. It consumes more memory and is slower to process.
DoubleConstants: Each method here uses a constant for the conversion. For regular stuff, these are fine.
Float64: The compiler will treat these constants internally as float64 values. These are in a static class, which doesn't store state.
Tip: Static classes are just a syntactic feature of the C# language, but they help clarify the code.
C# program that converts miles and kilometers
using System;
class Program
{
static void Main()
{
//
// Convert miles to kilometers.
//
double miles1 = 200;
double kilometers1 = ConvertDistance.ConvertMilesToKilometers(200);
Console.WriteLine("{0} = {1}", miles1, kilometers1);
//
// Convert kilometers to miles.
//
double kilometers2 = 321.9;
double miles2 = ConvertDistance.ConvertKilometersToMiles(321.9);
Console.WriteLine("{0} = {1}", kilometers2, miles2);
//
// Convert kilometers to miles (again).
//
double kilometers3 = 500;
double miles3 = ConvertDistance.ConvertKilometersToMiles(500);
Console.WriteLine("{0} = {1}", kilometers3, miles3);
//
// Convert miles to kilometers (again).
//
double miles4 = 310.7;
double kilometers4 = ConvertDistance.ConvertMilesToKilometers(310.7);
Console.WriteLine("{0} = {1}", miles4, kilometers4);
}
}
public static class ConvertDistance
{
public static double ConvertMilesToKilometers(double miles)
{
//
// Multiply by this constant and return the result.
//
return miles * 1.609344;
}
public static double ConvertKilometersToMiles(double kilometers)
{
//
// Multiply by this constant.
//
return kilometers * 0.621371192;
}
}
Output
200 = 321.8688
321.9 = 200.0193867048
500 = 310.685596
310.7 = 500.0231808
Info: The ldrc.r8 opcode pushes the supplied value (the 0.621371192) onto the stack as a float.
Method implementation: IL
.method public hidebysig static float64 ConvertKilometersToMiles(float64 k)
cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldc.r8 0.621371192
L_000a: mul
L_000b: ret
}
Review: We saw how the methods are converted into MSIL. We also used a static class to logically store static methods.