(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?