Search code examples
c#wpfstring.format

Using conditional operator with mixed data types in String.Format


I have a String.Format method that I want to insert either a string or an int, depending on whether a condition is met. My code looks like this:

Box.Text = String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt : "null"); 

So ideally, the method should check whether ScoreBoolCheck is true, and if so, insert student1.ScoreInt, but if not, it should insert the string "null" instead.

However, this doesn't work yet. I am getting an alert that says "there is no implicit conversion between int and string." Anyone see where I'm going wrong here? Thanks in advance for any help.


Solution

  • Just cast to object:

    Box.Text = String.Format("{0}", ScoreBoolCheck ? (object)student1.ScoreInt : "null");
    

    As there is an implicit conversion from string to object, this will work just fine. Assuming ScoreIntis an int, it will get boxed, but it would have been boxed anyway while passing parameters to String.Format (its last parameter is of type object[]).

    The conversion is required, as the ternary expression must have a type.

    You can't write:

    var x = someCondition ? 42 : Guid.NewGuid();
    

    Because no type could be assigned to x, as int and Guid aren't compatible (none of these can be assigned to the other one).

    But if you write:

    var x = someCondition ? (object)42 : Guid.NewGuid();
    

    Then x is unambiguously of type object. Guid can be implicitly boxed to object.