Pergunta

Check the code bellow:

class Money
{
    public Money(decimal amount)
    {
        Amount = amount;
    }

    public decimal Amount { get; set; }

    public static implicit operator decimal(Money money)
    {
        return money.Amount;
    }

    public static explicit operator int(Money money)
    {
        return (int)money.Amount;
    }
}

I don't understand how it would be useful in my code, couldn't I just do a method like:

public static int returnIntValueFrom(Money money)
{
    return (int)money.Amount;
}

Wouldn't it be easier and clearer to implement?

Foi útil?

Solução

This is done to allow for money to be added to other money. Without that piece of code, this would cause a compiler error, "Operator '+' cannot be applied to operands of type 'Money' and 'int'"

Money money = new Money(5.35m);
decimal net = money + 6;

With the casting operator present it allows these types of conversions to be made without throwing an exception. It can assist in readability and allow for polymorphism where different currencies could implement their own types of casts for example.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top