I have defined implicit string conversion from/to a certain type in C# (dummy code):
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;
}
}
Somewhere in external library code, an instance of MyType
is passed to a method, as an object
parameter. Part of that method looks like something along these lines:
private void Foo(object value)
{
// ... code omitted
var bar = value as string // note that value is an instance of MyType at runtime
if(bar != null) // false, cast fails
{
// ... code omitted
}
}
Why does the cast not use the implicit converter? I thought the whole point of these was to make casting and transparent usage possible?
Would this work if MyType
had an explicit
converter instead? If so, (how) can I have both?
By the way, the cast definitely works if the type is known at compile-time. Is this because operators are static
? Is there something like non-static conversion operators?
P.S. I'm actually most interested in the differences between compile-time behaviour and runtime behaviour, so I've a follow-up question: Why are implicit type conversion operators not dynamically usable at runtime 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.
See more on this question at Stackoverflow