Why does the "as" operator not use an implicit conversion operator in C#?
Why does the soft cast not use the implicit converter?
Well, that's the way the language is specified, basically. From the C# 5 specification section 7.10.11:
If the compile-time type of E is not dynamic, the operation E as T produces the same result as
E is T ? (T)(E) : (T)null
except that E is only evaluated once.
[...]
Note that some conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.
Imagine that an implicit conversion operator would have to get called. In this case, any call
var castObj = rawObj as SomeType;
would require the .NET runtime to use reflection in order to determine whether the "rawObj" object has a conversion operator. Obviously, this would be much more computationally expensive than just to check if the object is of type SomeType or its subtype. Better to have a fast and predictable operator than a more versatile, but much slower one.
as
keyword doesn't considers the user defined operators. You need to use a cast operator instead. Related article from Eric Lippert
In your case both explicit and implicit operators can't help you as you're trying to cast from object
to string
not from MyType
to string
. For user defined conversion operators to work, compile time type of the instance to be of type MyType
instead of object
. Because there is no conversion exist from object
to string
but from MyType
to string
.
The C# language Specification explicitly mentions this in the documentation for as
:
Note that some conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.
So you have to cast it.