Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 995
serhio Avatar asked Dec 05 '22 00:12

serhio


1 Answers

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.

like image 73
Mark Byers Avatar answered Dec 07 '22 14:12

Mark Byers