Home > Software design >  Operator '&&' cannot be applied to operands of type 'double' and 'double�
Operator '&&' cannot be applied to operands of type 'double' and 'double�

Time:09-16

I wrote the following code.

if (product1.cost > (product2.cost && product3.cost))
{

}

product1, product2, product3 are object names of class Product. cost is a public double type variable.

The below part shows the error :Operator '&&' cannot be applied to operands of type 'double' and 'double'

(product2.cost && product3.cost)

I was trying to find which product's cost is higher.

Click here to view the picture of the code in Visual Studio IDE

CodePudding user response:

I was trying to find which product's cost is higher.

No. Well, that is not what you SAY:

product1.cost > (product2.cost && product3.cost)

Compares the product1.cost to (product2.cost && product3.cost) and && is not defined.

If you want to compare p1.c to the other, you must say so:

(p1.c > p2.c) && (p1.c > p3.c)

While && is a shortcut, this does not mean you do not have to use proper syntax to say WHAT you want.

CodePudding user response:

The && operator is a logical operator that works on boolean operands only, which is why you're getting that error. In some languages there is an implicit conversion to boolean - C for instance interprets any non-zero value as true in this context - but C# is not one of those.

I was trying to find which product's cost is higher.

In that case you need one of the ordering comparisons: <, >, <= or >=. These compare two values and returns true or false. In your case the > operator:

if (product1.cost > product2.cost && product1.cost > product3.cost)
{
    // product1
}
else if (product 2.cost > product3.cost)
{
    // product2
}
else
{
    // product3
}

Depending on what you're doing there may be better ways to go. If you're just picking out the largest cost item and are going to perform the same operation regardless then LINQ is useful:

var product = new[] { product1, product2, product3 }
    .OrderByDescending(p => p.cost)
    .First();

For larger collections that's a much more concise way to go about it. It also extends nicely into database work. If you haven't encountered LINQ before, I encourage everyone to learn it. It's not always the best way, but it gives you additional options.

  •  Tags:  
  • c#
  • Related