As I was creating my Fraction class, I needed “an option” for automatic cast. Let’s see here what the problem was. When I want to represent an integer as a fraction, I have to do it like this:
1 |
Fraction f = new Fraction(5); |
But it is a little boring to type every time new Fraction(…). I wondered if there is a way when I type something like this
1 |
Fraction f = 5; |
the integer to be automatically converted to a fraction. Well, for my happiness, there is such an option. The implicit keyword is used to declare an implicit user-defined type conversion operator. And here it is my usage.
1 2 3 4 |
public static implicit operator Fraction(int number) { return new Fraction(number); } |
Now, I can simply use Fraction f = 5; and I have a fraction object. Really cool!