سؤال

My code is like this:

if (statusCode== "1")
{
    statusCode = productStatusItemAvailable1;
}
else if(statusCode =="2")
{
    statusCode = productStatusItemOutOfStock1;
}
 else if(statusCode =="3")
{
    statusCode = productStatusItemAvailableOnRemoteDate1;
}
else if(statusCode =="4")
{
    statusCode = productStatusAlternativeItemAvailable1;
}
else if(statusCode =="5")
{
    statusCode = productStatusItemSoldOutAndOurSuppliersHaveNoAvailable;
}
else if(statusCode =="6")
{
    statusCode = productStatusItemSoldOutContactCustomerService1;
}

To make it little more readable and easy to handle I tried to apply Ternary Operator

statusCode == "1"  ? productStatusItemAvailable1: "2" ? productStatusItemOutOfStock1 : "3" ? productStatusItemAvailableOnRemoteDate1  : "4"  ? productStatusAlternativeItemAvailable1 : "5" ? productStatusItemSoldOutAndOurSuppliersHaveNoAvailable : "6" ? productStatusItemSoldOutContactCustomerService1;

But this shows an error

Can not implicitly convert string to bool.

What am I doing wrong?Or is it not possible to use with strings?

هل كانت مفيدة؟

المحلول

As pointed out, you aren't checking the value against the string. That said, you should definitely use a switch statement for this:

switch(statusCode)
{

    case "1":
        // do some stuff
    break;

    // etc...
}

Though ideally, statusCode should be an enum where each value corresponds to the error, it will make your code clearer.

نصائح أخرى

You need a statuscode == for every condition

statusCode == "1" ? product1 : statusCode == "2" ? product2 ... etc

The sintaxe for ?: Ternary is:

object result = bool ? object : object;

In your code, you did not define anything after the : scope, to use like this, you could define another ternary scope after the : and apply it again, something like:

  statusCode  = statusCode == "1" ? productStatusItemAvailable1 : 
                statusCode == "2" ? productStatusItemOutOfStock1 : 
                statusCode == "3" ? productStatusItemAvailableOnRemoteDate1 : 
                statusCode == "4" ? productStatusAlternativeItemAvailable1 : 
                statusCode == "5" ? productStatusItemSoldOutAndOurSuppliersHaveNoAvailable : 
                statusCode == "6" ? productStatusItemSoldOutContactCustomerService1 
                : stirng.Empty;

The last : scope of ternary, is like the last else statment of an if structure. you have to define a value as a default value for it, because it is part of the structure of ternary operator.

You'd probably be better off using a switch statement, or a dictionary:

var statusCodes = new Dictionary<string, string>{};
statusCodes.Add("1", productStatusItemAvailable1); // For each message

Now you can get each message using the key:

// Will return value of productStatusItemAvailable1:
var result = statusCodes["1"]; 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top