2

I need to limit the value on overflow. I implemented this as follows:

    public static sbyte LimitValueToSByte(this int val)
    {
        if (val > sbyte.MaxValue) return sbyte.MaxValue;
        if (val < sbyte.MinValue) return sbyte.MinValue;
        return (sbyte)val;
    }

Is there a more elegant way?

This is the code in a time critical system, therefore performance is important.

4 Answers 4

3

That seems like a perfectly readable and valid code that doesn't need any improvement whatsoever. It's just the name of the method. Maybe use ToSbyte rather than LimitValueToSByte.

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

Comments

1

Can't think of a better way to write that function.

I'd call it ClampToSByte, since this kind of limiting operation is usually called Clamp. Limit is a bit less specific, and allows for other boundary conditions, such as wrapping around.

You should be careful if you implement similar code for floating point numbers. In particular you need to decide what behavior you want for NaNs and signed zeros. But luckily that are no issues with integral values.

5 Comments

Signed zeros shouldn't be an issue.
@Slaks Not with integers. But (-0.0).Clamp(0,1) returns -0 which might not be desired in all situations.
I'm aware of signed zeros, but they won't cause issues here. In .Net, -0.0 is indistinguishable from 0.0.
1/(-0.0) is different from 1/(+0.0). So they can lead to different results when they are used in calculations.
I take that back. However, it won't cause issues here, since he's just doing comparisons, and integer types don't have signed zeroes.
0

Looks pretty good to me. If you want something more elegant, how about a generic clamp function?

public static T Clamp<T>(this T value, T min, T max)
    where T : IComparable<T>
{
    if (value.CompareTo(min) <= 0) return min;
    if (value.CompareTo(max) >= 0) return max;
    return value;
}

(Warning: I didn't test this.) You could use it like this:

int a = 42;
sbyte b = (sbyte)a.Clamp(sbyte.MinValue, sbyte.MaxValue);

2 Comments

I'd use IComparable<T> to avoid boxing for value-types.
@CodeInChaos: I had no idea that would prevent boxing. Thanks.
0

My new solution of this problem:

public static sbyte Clamp(this int val)
{
    return (sbyte)Math.Max(Math.Min(value, sbyte.MaxValue), sbyte.MinValue);
}

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.