Viku
Viku

Reputation: 2973

Unable to cast to string

I wrote some code as below but in scenario - 1 , it throws an error in 2nd line stating can not implicitely convert type string to bool where as in scenario-2 it throws error stating cann not implicitely convert type bool? to bool.

Scenario - 1 
    string Test = Employee.IsPermanent ? "Permanent" : "";
    Test = Test + Employee.IsClear ? "Clear" : "";  //Throws error
 scenario - 2

    Test = Test + (Employee.IsClear ? "Clear" : "") + (Employee.IsPermanent ? "Permanent" : "") + ( Employee.IsSalaried ? "Salaried" : ""); //Throws error

Note - IsPermanent and IsClear are boolean variable where as IsSalaried is nullable boolean variable .

Upvotes: 0

Views: 53

Answers (3)

Luc
Luc

Reputation: 1491

The error shows that you try to convert a nullable boolean to a boolean, which you do in this statement:

(Employee.IsSalaried ? "Salaried" : ""); 

You should check if it has a value:

 ((Employee.IsSalaried.hasValue && Employee.IsSalaried.Value) ? "Salaried" : ""); 

Upvotes: 2

Christos
Christos

Reputation: 53958

If you place this Employee.IsClear ? "Clear" : "" inside a parenthesis, it will work.

Test = Test + (Employee.IsClear ? "Clear" : ""); 

This is happening because the + will be evaluated first. So this result would be a string and from the left side of the conditional operator you would have a string instead of a bool or an expression that can be evaluate to a boolean value.

On the other hand, using a parenthesis the expression inside the parenthesis would be evaluated first and then the result would be concatenated with the Test .

This has to do with the precedence of the operators. A detailed explanation can be found here.

Upvotes: 3

Szabolcs Dézsi
Szabolcs Dézsi

Reputation: 8843

Test = Test + (Employee.IsClear ? "Clear" : "");

The precedence of operators can be found here

Upvotes: 1

Related Questions