Explicit keyword in c#

The explicit keyword is used to declare an explicit user-defined type conversion operator

 class Celsius
    {
        public Celsius(float temp)
        {
            degrees = temp;
        }
// define explicit Celsius-to-Fahrenheit conversion operator:
        public static explicit operator Fahrenheit(Celsius c)
        {
            return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
        }
        public float Degrees
        {
            get { return degrees; }
        }
        private float degrees;
    }

    class Fahrenheit
    {
        public Fahrenheit(float temp)
        {
            degrees = temp;
        }
// define explicit Fahrenheit-to-Celsius conversion operator:
        public static explicit operator Celsius(Fahrenheit f)
        {
            return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
        }
        public float Degrees
        {
            get { return degrees; }
        }
        private float degrees;
    }

static void Main(string[] args)
        {
                Fahrenheit f = new Fahrenheit(100.0f);
                Console.Write("{0} fahrenheit", f.Degrees);
                Celsius c = (Celsius)f;// explicit conversion
                Console.Write(" = {0} celsius", c.Degrees);
                Fahrenheit f2 = (Fahrenheit)c;// explicit conversion
                Console.WriteLine(" = {0} fahrenheit", f2.Degrees);      
        }

Comments

Post a Comment

Popular posts from this blog

How to get motherboard serial number, Processor ID, VolumeSerialNumber using C#?

Fiserv Interview Questions.

AngularJs - Simple Example