Temperature conversion class in C#

ddanbe

Class to convert between Celcius, Fahrenheit and Kelvin temperatures.
Set one temperature and automatically get the other two.
This class makes use of properties. See the code snippet for details.
A short main program is added to exercise the Temperature class by printing a conversion table between celsius and fahrenheit.

1,405 Views
About the Author

Have programmed in Modula-2 on a professional basis in the eighties. Now I am quite fond of C# AND Python!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_Temperature
{
    class Temperature
    {
        private const double cAbsTempC = 273.15;//absolute temperature in Celcius
        private const double cAbsTempF = 459.67;//absolute temperature in Fahrenheit

        private double _Kelvin = 0.0; 

        public Temperature(){}

        public Temperature(double kelvintemp)
        {
            _Kelvin = kelvintemp;
        }

        public double Celcius 
        {
            get { return _Kelvin - cAbsTempC; }
            set { _Kelvin = value + cAbsTempC; }
        }

        public double Fahrenheit
        {
            get { return _Kelvin*9/5 - cAbsTempF; }
            set { _Kelvin = (value + cAbsTempC)*5/9; }
        }

        public double Kelvin
        {
            get { return _Kelvin; }
            set { _Kelvin = value; }
        }
    }

  class Program
    {
        static void Main(string[] args)
        {
            // print a table from 0 to 10 degrees C,
            // with the conversion to Fahrenheit degrees,
            // using the Temperature class
            Temperature temp = new Temperature();
            Console.WriteLine("Celcius \t Fahrenheit");
            Console.WriteLine();
            for (int i = 0; i <= 10; i++)
            {
                temp.Celcius = i;
                Console.WriteLine("{0}  \t  {1}", temp.Celcius, temp.Fahrenheit);
            }
            Console.ReadKey();
        }
    }
}
MosaicFuneral 812 Nearly a Posting Virtuoso

Try the constant 1.8 , instead of the fraction.

ddanbe 2,724 Professional Procrastinator Featured Poster

You are right MosaicFuneral. If we can avoid division we must!
I left 5/9 and 9/5 in because it is clearer to understand. I a real situation I would also use 1.8 and 0.55555.
Btw. the absolute temp constants are in a way not correct either!
Real absolute temps are negative, but here the calculations done are correct.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.