Tag Archives: implicit operator conversion cast
Implicit Operator
Published on February 2nd, 2008.
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:
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
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.
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!
Filled under C#. No Comments.