Convert Temperature

Description: Converts double values between one of three temperature units: Celsius, Fahrenheit and Kelvin.
Tested Platform: .NET 4.6, Visual Studio 2015, Windows 7/10
Language: C#
// Enum to make temperature conversion more readable.
enum Temp {
    Celsius = 1,
    Fahrenheit = 2, 
    Kelvin = 3
}

// Converts temperature values between three units, Celcius, Fahrenheit and Kelvin.
private double ConvertTemp(double value, Temp fromUnit, Temp toUnit) {
    if (fromUnit == Temp.Fahrenheit) {
        if (toUnit == Temp.Celsius) { return (value - 32.0) * (5.0 / 9.0); }
        else if (toUnit == Temp.Kelvin) { return (((value - 32.0) * 5) / 9) + 273.15; }
    }
    else if (fromUnit == Temp.Celsius) {
        if (toUnit == Temp.Fahrenheit) { return (value * (9.0 / 5.0)) + 32.0; }
        else if (toUnit == Temp.Kelvin) { return value + 273.15; }
    }
    else if (fromUnit == Temp.Kelvin) {
        if (toUnit == Temp.Fahrenheit) { return (((value - 273.15) * 9) / 5) + 32.0; }
        else if (toUnit == Temp.Celsius) { return value - 273.15; }
    }

    return value;
}

Submitted: November 09, 2012

Return to the snippets listing