Search code examples
c#typecast-operator

no typecast operator for class in c#?


typecast operator is cool in c++, no such thing in c#?

c++ code:

class A
{
int dat;

public:
A(int num = 0 ) : dat(num) {}

operator int() {return dat;} // cast to int
};

Solution

  • C# has! here couple examples from MSDN: Explicit:

    public static explicit operator Celsius(Farenheit f)
    {
        return new Celsius((5.0f/9.0f)*(f.degrees-32));
    }
    

    Implicit:

    //  User-defined conversion from double to Digit
    public static implicit operator Digit(double d)
    {
        return new Digit(d);
    }