# 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%). – Clockwork-Muse Feb 25 '13 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. – BjarkeCK Feb 26 '13 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 ! – BjarkeCK Feb 25 '13 at 23:43
• Jeez, I think this is the first XNA code review I've seen. Glad I could help. – Reacher Gilt Feb 26 '13 at 16:05
• Why IComparable instead of IComparable<T>? And I'd use Comparer<T>.Default.Compare over left.CompareTo(right). – CodesInChaos Feb 27 '13 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. – Reacher Gilt Feb 27 '13 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 – almaz Feb 26 '13 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. – almaz Feb 26 '13 at 21:20