Search code examples
c#.netoperatorsternary-operator

C# ? : operator


Could somebody explain me the following compiler issue

Error: Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'

// WORKS
string text = string.Format(
    "the id is {0}", _Obj.Id.ToString());

// WORKS, without implicit conversion <<<
string text = string.Format(
    "the id is {0}", _Obj.Id);

// WORKS
string text = string.Format(
    "the id is {0}", (_Obj == null) ? "unknown" : _Obj.Id.ToString());

// NO WAY <<<
string text = string.Format(
    "the id is {0}", (_Obj == null) ? "unknown" : _Obj.Id);

in the last example, there is no implicit conversion, as well.


Solution

  • See Eric Lippert's blog article Cast operators do not obey the distributive law.