0

(This is a follow-up question to: Why does the "as" operator not use an implicit conversion operator in C#?).

Consider a type with implicit conversion operators:

public class MyType
{
    public string Value { get; set; }

    public static implicit operator MyType(string fromString)
    {
        return new MyType { Value = fromString };
    }

    public static implicit operator string(MyType myType)
    {
        return myType.Value;
    }
}

Now consider the following usage of it:

void Main()
{
    MyType myTypeCompiletime = (MyType)"test";
    object myTypeRuntime = (MyType)"test";

    var conv1 = (string)myTypeCompiletime;
    var conv2 = (string)myTypeRuntime; // InvalidCastException

    // false, while technically true
    var assignable = myTypeCompiletime.GetType().IsAssignableFrom(typeof(string));
}

There is clearly a different behaviour between compile-time and runtime. Why? Is there something I can do to make the same runtime behaviour possible?

Community
  • 1
  • 1
MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • I have marked your question as a duplicate since the part *"is there something I can do..."* is answered in the other question. If you feel that this is in error (or you are actually more interested in the *why* part and the other question does not answer this to your satisfaction), please say so and I will reopen it. – Heinzi Feb 19 '16 at 16:06
  • @Heinzi the answer on the other question satisfies my curiosity. Sorry for missing the duplicate but it never showed up in google with the terms I was using. – MarioDS Feb 19 '16 at 16:07
  • 2
    No problem. Duplicates are not necessarily a bad thing -- now other people googling this problem are more likely to find their answer. – Heinzi Feb 19 '16 at 16:09

0 Answers0