Created
March 11, 2024 03:04
-
-
Save Calabonga/cb845a5c675a0e848d7a31c7d36a35e0 to your computer and use it in GitHub Desktop.
Implicit operators demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public struct Money | |
{ | |
private readonly double _amount; | |
public Money(double amount) | |
{ | |
_amount = amount; | |
} | |
public double Amount => _amount; | |
// Implicitly converts Money to double | |
public static implicit operator double(Money money) | |
{ | |
return money._amount; | |
} | |
// Implicitly converts double to Money | |
public static implicit operator Money(double amount) | |
{ | |
return new Money(amount); | |
} | |
} | |
// Usage | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Money moneyInWallet = new Money(100.50); // $100.50 | |
double cash = moneyInWallet; // Implicit conversion to double | |
// Adding more money | |
moneyInWallet += 99.50; // Implicit conversion from double to Money, then addition | |
Console.WriteLine(cash); // Output: 100.5 | |
Console.WriteLine(moneyInWallet.Amount); // Output: 200 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment