This question already has an answer here:
- Order of implicit conversions in c# 1 answer
Consider the following code:
public class Test
{
public static implicit operator int(Test t) { return 42; }
public override string ToString() { return "Test here!"; }
}
var test = new Test();
Console.WriteLine(test); // 42
Console.WriteLine((Test)test); // 42
Console.WriteLine((int)test); // 42
Console.WriteLine(test.ToString()); // "Test here!"
Why in the first three cases we have answer 42
even if we explicitly cast to Test
?
Does implicit
operator have higher priority over ToString()
?
Yes. Implicit operators have precedence over explicit operators. The language specification states that implicit operators should not loose information, while this is allowed for explicit operators. See for instance, MSDN explicit. If you change the keyword
implicit
toexplicit
you will seeTest here!
3 times, and 42 once.