david_10001 david_10001 - 3 years ago 185
C# Question

Set function ignoring if statement - should be returning 0 if input is less than or equal to 0

I have quite a simple task, to use a get and set function/method (not sure what you call it) in C# to return values in a certain range. If the input value is below or equal to 0, the returned value should be 0, and if the input value is greater than or equal to 100, it should return 100. All input values in between 0 and 100 are just directly returned as they are.

The problem is if I enter a negative number as my input, it is not changing it to zero. The funny thing is my maximum function is working fine, even though it is just the opposite of my minimum.

Can someone tell me why my first if statement is not changing the negative value to zero?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RangeRestrictedInteger
{
public class RangedInteger
{
int minimum;
int maximum;
int valueReturn;

public RangedInteger(int min, int max)
{
minimum = min;
maximum = max;
}

public int Value
{
get
{
return valueReturn;
}
set
{
if (value <= minimum)
{
valueReturn = minimum;
}
if (value >= maximum)
{
valueReturn = maximum;
}
else
{
valueReturn = value;
}
}
}
}
class Program
{
static void Main(string[] args)
{
RangedInteger myInteger = new RangedInteger(0, 100);
myInteger.Value = 57;
Console.WriteLine("{0}", myInteger.Value); // Should be 57
myInteger.Value = 103;
Console.WriteLine("{0}", myInteger.Value); // Should be 100
myInteger.Value = -4;
Console.WriteLine("{0}", myInteger.Value); // Should be 0

Console.WriteLine("\nPress enter to exit.");
Console.ReadLine();
}
}
}

Answer Source

This happens because your first and second ifs are not exclusive: the final else of the second if will be executed even when the first if is executed.

Add an extra else to fix this problem:

if (value <= minimum)
{
    valueReturn = minimum;
}
else if (value >= maximum)
{
    valueReturn = maximum;
}
else
{
    valueReturn = value;
}

Note that you can avoid this problem altogether by using Math.Min and Math.Max

set {
    valueReturn = Math.Min(Math.Max(value, minimum), maximum);
}

Demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download