Skip to content

Tag: temperature

C# class properties example

A example of use of C# class properties to convert temperatures in Celsius, Fahrenheit or Kelvin. The temperature is encapsulated and stored in a internal representation, in this example, in Celcius (private double c). Each conversion is accessible by getting or setting a property.

using System;

public class Temperature {
	private double c;

	public double celsius {
		get {
			return c;
		}
		set {
			c = value;
		}
	}

	public double fahrenheit {
		get {
			return (c * 9 / 5) + 32;
		}
		set {
			c = (value - 32) * 5 / 9;
		}
	}

	public double kelvin {
		get {
			return c + 273.15;
		}
		set {
			c = value - 273.15;
		}
	}
}

public class TemperatureExample {
	public static void Main(string[] args) {
		Temperature fortaleza = new Temperature();
		fortaleza.celsius = 26;

		Temperature washington = new Temperature();
		washington.fahrenheit = 32;

		Temperature sun = new Temperature();
		sun.kelvin = 5778;

		Console.WriteLine("Fortaleza {0}°C / {1}°F / {2} K",
			fortaleza.celsius, fortaleza.fahrenheit, fortaleza.kelvin);
		Console.WriteLine("Washington {0}°C / {1}°F / {2} K",
			washington.celsius, washington.fahrenheit, washington.kelvin);
		Console.WriteLine("Sun {0}°C / {1}°F / {2} K",
			sun.celsius, sun.fahrenheit, sun.kelvin);
	}
}

Output:

Fortaleza 26°C / 78.8°F / 299.15 K
Washington 0°C / 32°F / 273.15 K
Sun 5504.85°C / 9940.73°F / 5778 K

There is some good examples of C# class properties at Using Properties (C# Programming Guide) at MSDN.