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.
The problem is nothing to do with your usage of string.Format
. The problem is this expression:
(_Obj == null) ? "unknown" : _Obj.Id
The compiler cannot determine the type of this expression because there is no implicit conversion between int
and string
. You have already found the solution - calling ToString
means that the expression returns a string
in either case. Another way you could have fixed it (but slightly less efficient in this case because of boxing) is to tell the compiler explicitly how to perform the conversion. For example, you can use an explicit cast to object
:
(_Obj == null) ? "unknown" : (object)_Obj.Id
Your second example works without an explicit cast because string.Format
expects an object
and there is an implicit conversion from int
to object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With