0

I create a function to compare the price of my item. This is my function:

public static decimal ComparePrice(decimal Price, decimal WebsitePrice)
    {
        decimal ZERO_PRICE = 0.00000M;
        if(Price == ZERO_PRICE && WebsitePrice > ZERO_PRICE){
            return WebsitePrice;
        }else if(Price == ZERO_PRICE && WebsitePrice == ZERO_PRICE){
            return "";
        }else{
            return Price;
        }

    }

if the both(price and websiteprice) is equal 0.00, then it will return the empty string, I know it is not possible to return the string while the function is set to decimal type, but i have no idea what should I do about that. Anyone can help? Thanks.

4 Answers 4

6

If it makes sense in your application logic, you can use a Nullable type and use null instead of an empty string. Like :

public static decimal? ComparePrice(decimal Price, decimal WebsitePrice)
    {
        if(Price == decimal.Zero && WebsitePrice > decimal.Zero){
            return WebsitePrice;
        }else if(Price == decimal.Zero && WebsitePrice == decimal.Zero){
            return null;
        }else{
            return Price;
        }

    }

Or use Decimal.MinValue as suggested as a flag for invalid. (I like the null better, again, just if this is actually a valid value in your logic).

Sign up to request clarification or add additional context in comments.

Comments

2

Why dont you return simple 0.0 Of course when both values are 0.0 .. returning 0.0 make sense.

2 Comments

umm... If I return 0.0, then I have to test again in my view, if the return value = 0.0 , then display empty string. Because all the items should not display its price = 0.0.
consider using nullable types as suggested by anthony and Francisco.
2

C# has had nullable types for quite a while now, try defining your method like this and returning null for the case in question:

public static decimal? ComparePrice(decimal Price, decimal WebsitePrice)

1 Comment

+1 for using standard ways of implementing this functionality.
1

You could always return something like decimal.MinValue that would indicate they were both a zero price item.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.