Reputation: 71
I am getting an Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' on the if statements in the GetPrice method. It shows its highlighted on all the "if (size == "Small")" statements. Here are my variables:
drinkType = GetDrinkType();
size = GetDrinkSize();
price = GetPrice(size);
private string GetDrinkType()
{
string theDrink;
theDrink = "None Selected";
if (rdoCoffee.Checked)
{
theDrink = "Coffee";
}
else if (rdoCoco.Checked)
{
theDrink = "Hot Chocolate";
}
else if (rdoSmoothie.Checked)
{
theDrink = "Smoothie";
}
return theDrink;
}
private string GetDrinkSize()
{
string theSize;
theSize = "None Selected";
if (rdoSmall.Checked)
{
theSize = "Small";
}
else if (rdoMedium.Checked)
{
theSize = "Medium";
}
else if (rdoLarge.Checked)
{
theSize = "Large";
}
return theSize;
}
private decimal GetPrice(object size)
{
decimal thePrice;
thePrice = 0;
if (size == "Small")
{
thePrice = 1.25m;
}
else if (size == "Medium")
{
thePrice = 2.50m;
}
else if (size == "Large")
{
thePrice = 3.35m;
}
return thePrice;
}
Upvotes: 1
Views: 1461
Reputation: 31097
Since in GetPrize
, the type of size
is object
, but you are comparing it to a string
with size == "Large"
.
Change the comparison with "string text".Equals(object)
as shown below
private decimal GetPrice(object size)
{
decimal thePrice = 0m;
if ("Small".Equals(size))
{
thePrice = 1.25m;
}
else if ("Medium".Equals(size))
{
thePrice = 2.50m;
}
else if ("Large".Equals(size))
{
thePrice = 3.35m;
}
return thePrice;
}
Upvotes: 0
Reputation: 292555
The size
parameter is declared of type object
, so the compiler doesn't know it's actually of type string
. So it uses the default equality for type object
, which is a reference comparison.
If you change the type of size
to string
, it will use the equality operator overload from the string
class, which performs a value comparison.
private decimal GetPrice(string size)
Upvotes: 3
Reputation: 3133
The warning occurs because you are comparing a string to an object. If you change
if (size == "Small")
to
if (size.ToString() == "Small")
the warning will be removed.
Upvotes: 1