.Net C# using the Implicit keyword

A simple program to demonstrate using the C# Implicit keyword.

using System;

namespace CsharpImplicitKeyWordDemo
{
    /// <summary>
    /// Class to demonstrate the C# Implicit operator
    /// </summary>
    public class CsharpImplicitKeyWordExample
    {
        static void Main()
        {
            var number = new Number(42);

            // Implicit Double 
            long longNumber = number;

            // Implicit Number 
            const int aNumber = 21;

            Console.WriteLine("{0} : {1}", longNumber, aNumber);

            Console.ReadLine();
        }
    }

    /// <summary>
    /// Class implementing the Implicit keyword.
    /// </summary>
    internal class Number
    {
        /// <summary>
        /// The _value
        /// </summary>
        private readonly long _value;

        /// <summary>
        /// Initializes a new instance of the <see cref="Number"/> class.
        /// </summary>
        /// <param name="number">The command.</param>
        public Number(long number)
        {
            _value = number;
        }

        /// <summary>
        /// Return a long number.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <returns>a Long</returns>
        public static implicit operator long(Number number)
        {
            return number._value;
        }

        /// <summary>
        /// Return the input as the Number type.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <returns>a Number</returns>
        public static implicit operator Number(long number)
        {
            return new Number(number);
        }
    }
}

Returns:

42 : 21

Leave a Reply

Your email address will not be published. Required fields are marked *