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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With