Search code examples
.netoperator-overloadingconversion-operator

.net operator overloading??? type conversion operator, how exactly it works?


I have first encounter operator overloading in .Net, long back I had used it in C++, but that was like overloading operators like "+", now I have suddenly scenario as below.

I have a struct AccessToken:

[StructLayout(LayoutKind.Sequential)]
public struct AccessToken : IConvertible
{
    private string _value;
    public AccessToken(string encodedAccessToken)
    {
        this._value = encodedAccessToken;
    }

    public static implicit operator AccessToken(string encodedAccessToken)
    {
        return new AccessToken(encodedAccessToken);
    }
}

I understood the first method is a constructor, but I was wondering exactly 2nd one is doing? Definitely some kind of operator overloading. I read http://msdn.microsoft.com/en-us/library/s53ehcz3(v=vs.71).aspx but could not get exact idea.


Solution

  • It's an implicit conversion from string to AccessToken. So you could write:

    string foo = "asdasd";
    AccessToken token = foo;
    

    That would invoke the second member - the implicit conversion operator. Without that being present, the above code wouldn't compile, as there would be no conversion available from string to AccessToken.

    Personally I would advise you to be very careful with implicit conversions - they can make code much harder to understand. Just occasionally they can be very useful (LINQ to XML springs to mind) but I would normally just go with constructors or static factory methods.