कंप्यूटर प्रोग्रामिंग/ऑब्जेक्ट्स/सी शार्प

विकिविश्वविद्यालय से

objects.cs[सम्पादन | स्रोत सम्पादित करें]

// This program creates instances of the Temperature class to convert Cesius
// and Fahrenheit temperatures.

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;
    }
}

कोशिश करो[सम्पादन | स्रोत सम्पादित करें]

निम्न कोड मुफ्त ऑनलाइन विकास के वातावरण में से एक में ऊपर कॉपी और पेस्ट करो या अपने खुद के कम्पाइलर/इंटरप्रेटर/आईडीई का उपयोग करें।

यह भी देखें[सम्पादन | स्रोत सम्पादित करें]