csharp implicit operator

Code Example - csharp implicit operator

                
                        public static implicit operator byte(Digit d) => d.digit;
    public static explicit operator Digit(byte b) => new Digit(b);
                    
                
 

what is implicit keyword csharp

                        
                                //Ability to assign a non-primitive instance a certain value,
//and to assign a primitave from the object

//Usage example:
Currency c = 10.5;
double myMoneyAmount = c;
//Also can further more do:
c = "%%%~COMPRESS~PRE~1~%%%quot;;
string currencyType = c;


//Impl example

/// <span class="code-SummaryComment"><summary></span>
/// Creates Currency object from string supplied as currency sign.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The currency sign like $,£,¥,€,Rs etc. </param></span>
/// <span class="code-SummaryComment"><returns>Returns new Currency object.</returns></span>
public static implicit operator Currency(string rhs)
{ 
    Currency c = new Currency(0, rhs); //Internally call Currency constructor
    return c;

}

/// <span class="code-SummaryComment"><summary></span>
/// Creates a currency object from decimal value. 
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The currency value in decimal.</param></span>
/// <span class="code-SummaryComment"><returns>Returns new Currency object.</returns></span>
public static implicit operator Currency(decimal rhs)
{
    Currency c = new Currency(rhs, NumberFormatInfo.CurrentInfo.CurrencySymbol);
    return c;

/// <span class="code-SummaryComment"><summary></span>
/// Creates a decimal value from Currency object,
/// used to assign currency to decimal.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The Currency object.</param></span>
/// <span class="code-SummaryComment"><returns>Returns decimal value of the currency</returns></span>
public static implicit operator decimal(Currency rhs)
{
    return rhs.Value;
}

/// <span class="code-SummaryComment"><summary></span>
/// Creates a long value from Currency object, used to assign currency to long.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The Currency object.</param></span>
/// <span class="code-SummaryComment"><returns>Returns long value of the currency</returns></span>
public static implicit operator long(Currency rhs)
{
    return (long)rhs.Value;
}
                            
                        
 

Related code examples