# Determine if an int is within range

Can I somehow make this a bit cleaner using Math.[Something], without making a method for it?

int MaxSpeed = 50;

if (Speed.X > MaxSpeed)
Speed.X = MaxSpeed;

if (Speed.X < MaxSpeed * -1)
Speed.X = MaxSpeed * -1;

if (Speed.Y > MaxSpeed)
Speed.Y = MaxSpeed;

if (Speed.Y < MaxSpeed * -1)
Speed.Y = MaxSpeed * -1;

• hmmm - please note: if you're using this to control speed in a 'non-grid' environment, the moving object will move faster than MaxSpeed in a diagonal direction (by about 40%). Commented Feb 25, 2013 at 23:49
• ah didn't think about that. tahts true. But up an down is only used for falling and jumping. and will have other max/min values. Commented Feb 26, 2013 at 0:01

There's a method in XNA called MathHelper.Clamp that does what you need. I understand if you don't want to import XNA libraries for this one function, though. You can do this with extension methods. Here's an implementation that uses generics (so you can apply it to various types) so you can use it for ints, longs, anything that implements IComparable

static class Extensions
{
public static T Clamp<T> (this T self, T min, T max) where T: IComparable
{
if (self.CompareTo( min) <0)
return min;
return self.CompareTo(max) > 0 ? max : self;
}
}

• Thanks, check out my tags, actually this is for a XNA project so MathHelper.Clamp was exactly what i was looking for, thank you for the code aswell ! Commented Feb 25, 2013 at 23:43
• Jeez, I think this is the first XNA code review I've seen. Glad I could help. Commented Feb 26, 2013 at 16:05
• Why IComparable instead of IComparable<T>? And I'd use Comparer<T>.Default.Compare over left.CompareTo(right). Commented Feb 27, 2013 at 22:37
• @CodesInChaos an interesting point wrt Comparer<t>.Default.Compare. I've only seen it used to safeguard against comparisons against null, but it'd totally be valid here too. Commented Feb 27, 2013 at 22:58

I'm afraid there is no such built-in method. There is a similar question here where an extension method is proposed to force the number to be in range (copy-pasting it with cosmetic changes here):

public static class InputExtensions
{
public static int LimitToRange(this int value, int inclusiveMinimum, int inclusiveMaximum)
{
if (value < inclusiveMinimum)
return inclusiveMinimum;
if (value > inclusiveMaximum)
return inclusiveMaximum;
return value;
}
}

• @Leonid System.Int32 and int are synonyms, or to be precise int is the C# alias for .NET type System.Int32, see description here Commented Feb 26, 2013 at 7:36
• @Leonid Not sure about your feeling, they are absolutely the same. And I don't see any issues in creating extension method for a "primitive", as well as not sure why you mentioned boxing here. Commented Feb 26, 2013 at 21:20