Programming Fundamentals/Objects/C Sharp

From Wikiversity
Jump to navigation Jump to search

objects.cs[edit]

// This program creates instances of the Temperature class to convert Celsius 
// and Fahrenheit temperatures.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Sharp_Programming

using System;

public class Objects  
{
    public static void Main(String[] args)
    {
        Temperature temp1 = new Temperature(celsius: 0);
        Console.WriteLine("temp1.Celsius = " + temp1.Celsius.ToString());
        Console.WriteLine("temp1.Fahrenheit = " + temp1.Fahrenheit.ToString());
        Console.WriteLine("");
    
        temp1.Celsius = 100;
        Console.WriteLine("temp1.Celsius = " + temp1.Celsius.ToString());
        Console.WriteLine("temp1.Fahrenheit = " + temp1.Fahrenheit.ToString());
        Console.WriteLine("");
        
        Temperature temp2 = new Temperature(fahrenheit: 0);
        Console.WriteLine("temp2.Fahrenheit = " + temp2.Fahrenheit.ToString());
        Console.WriteLine("temp2.Celsius = " + temp2.Celsius.ToString());
        Console.WriteLine("");
    
        temp2.Fahrenheit = 100;
        Console.WriteLine("temp2.Fahrenheit = " + temp2.Fahrenheit.ToString());
        Console.WriteLine("temp2.Celsius = " + temp2.Celsius.ToString());
    }
}

// This class converts temperature between Celsius and Fahrenheit.
// It may be used by assigning a value to either Celsius or Fahrenheit 
// and then retrieving the other value, or by calling the ToCelsius or
// ToFahrenheit methods directly.

public class Temperature
{
    double _celsius;
    double _fahrenheit;

    public double Celsius
    {
        get
        {
            return _celsius;
        }
        
        set
        {
            _celsius = value;
            _fahrenheit = ToFahrenheit(value);
        }
    }
    
    public double Fahrenheit
    {
        get
        {
            return _fahrenheit;
        }
        
        set
        {
            _fahrenheit = value;
            _celsius = ToCelsius(value);
        }
    }
    
    public Temperature(double? celsius = null, double? fahrenheit = null)
    {
        if (celsius.HasValue)
        {
            this.Celsius = Convert.ToDouble(celsius);
        }
        
        if (fahrenheit.HasValue)
        {
            this.Fahrenheit = Convert.ToDouble(fahrenheit);
        }
    }

    public double ToCelsius(double fahrenheit)
    {
        return (fahrenheit - 32) * 5 / 9;
    }
    
    public double ToFahrenheit(double celsius)
    {
        return celsius * 9 / 5 + 32;
    }
}

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own C Sharp compiler / interpreter / IDE.

See Also[edit]