Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use implicit/explicit operator?

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?

like image 923
Marcel James Avatar asked Aug 12 '13 23:08

Marcel James


People also ask

What is implicit operator in C#?

According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.

What is explicit keyword in C#?

The explicit keyword is used to create type conversion operators that can only be used by specifying an explicit type cast. This construct is useful to help software developers write more readable code. Having an explicit cast name makes it clear that a conversion is taking place.

What is an implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

What is a conversion operator?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.


1 Answers

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.

like image 179
Travis J Avatar answered Sep 30 '22 14:09

Travis J