Pritesh
Pritesh

Reputation: 1970

.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.

Upvotes: 2

Views: 135

Answers (2)

faester
faester

Reputation: 15076

The implicit operator allows you to assign an instance of type A to type B with a conversion defined in type A.

It can simplify your code a bit since you don't have to call conversion methods etc but can type B b = new A(); even though A doesn't inherit B.

I think it tends to introduce confusion though and prefer more explicit casts and conversions.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500365

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.

Upvotes: 1

Related Questions