CodeBlanks Logo Icon CodeBlanks

Number helpers

C# course · Intermediate · Lesson 21/116

Add number conversion and calculation methods.

Number helpers

Our second helper is Clamp: it keeps a number within a given range. If the value is in range it is unchanged; if below min it becomes min; if above max it becomes max. Declaration: public static int Clamp(int value, int min, int max).

Example: Helpers.Clamp(15, 0, 10) returns 10 because 15 is greater than 10. Helpers.Clamp(-3, 0, 10) returns 0. This is useful to keep user input or a game score in a safe range.

Using Clamp

Real-world uses of Clamp include keeping a percentage within 0-100 (Clamp(percent, 0, 100)), limiting a game level to 1-99, or pulling a color channel into 0-255.

The body is three simple conditions: if (value < min) return min;, if (value > max) return max;, return value;. This structure is clear, fast, and predictable. No complex math needed.

Exercise Add the Clamp method and call it

The Helpers class below already has Capitalize. Now add a public static int Clamp(int value, int min, int max) method. In the body write if (value < min) return min;, if (value > max) return max;, return value;. Inside Main print Helpers.Clamp(15, 0, 10).

Show example solution
Add the Clamp method to Helpers. In Main write Console.WriteLine(Helpers.Clamp(15, 0, 10));
Example solution:
using System;

static class Helpers
{
    public static string Capitalize(string text)
    {
        if (string.IsNullOrEmpty(text)) return text;
        return char.ToUpper(text[0]) + text.Substring(1);
    }

    public static int Clamp(int value, int min, int max)
    {
        if (value < min) return min;
        if (value > max) return max;
        return value;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Ready");
        Console.WriteLine(Helpers.Capitalize("hello"));
        Console.WriteLine(Helpers.Clamp(15, 0, 10));
    }
}

Test yourself

  1. Complete the Clamp body

    if (value < min) return ____;
    Show answer
    if (value < min) return min;
  2. What is Helpers.Clamp(15, 0, 10)?

    public static int Clamp(int value, int min, int max) { ... }
    • 15
    • 0
    • 5
    • 10
    Show answer

    10 — Correct. Since 15 is greater than 10, the max value 10 is returned.

  3. Match each method to its behavior

    Clamp
    Squeezes into range
    Min
    Takes the smallest
    Max
    Takes the largest
    Abs
    Absolute value

All lessons in Intermediate