Xyon (xyon) wrote,

Implicit cast operators

Okay, I've done some things in C# where defining the explicit or implicit cast operators was very handy.

I've also worked with serialization, where you wish it would run through your implicit cast operator, but, alas, no.

Anyways, I know when there are times that you want to mark an implicit cast operator because, well, your object is "virtually the same" as some other object. However, there are rules. The rules are: Don't be dumb.

Here is an example of being dumb:

public static implicit operator string(Foo foo) // This one is safe, it returns the underlying data representation as a string (okay, it can throw exceptions in rare cases; but they're well, exceptional)
public static implicit operator List<int>(Foo foo) // This one can throw FormatExceptions, can you guess why?
public static implicit operator List<SomethingElse>(Foo foo) // This one won't actually throw format exceptions, but you can get back a list of non-intuitive length and it contains, essentially, default(SomethingElse) elements.
public static implicit operator bool(Foo foo) { return ToString().Equals("true"); } // Well, at least it's safe from a format exception.

I would probably think it weird but move on if these were -explicit- cast operators -- you only get into trouble when you Do The Wrong Thing. But they're implicit operators, suggesting that "it just works"; or to someone unfamiliar with your stuff that Foo really is a List and you can just trust it. Oh, it's context sensitive? Oh, there's no way to see if the data is actually conforming before trying it? How brittle is this thing? Oh, can I have a new work item now?
  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.