C#
Putting it together
Combine helper methods into a single class.
Putting it together
You have reached the end of five lessons. The Helpers static class now has three helper methods: Capitalize, Clamp and FormatDate. In this final lesson you will call all of them together.
The power of a helper library comes from methods being used together. For example, you can fix a user-entered name with Capitalize, squeeze their age into 0-120 with Clamp, and print their registration date in standard form with FormatDate. All from one class.
Using helpers together
Calling the three methods together shows how Helpers works as a toolkit. Each handles a separate task; together they form a user-record cleanup flow.
Extending this later is easy: to add a new helper, you just write a method in the class. The callers do not change, the class name does not change. That is the mark of a well-designed library: simple to extend, easy to use.
Exercise Call all three helpers together
The Helpers class below has all three helpers ready. Inside Main call all three and print their results: Helpers.Capitalize("hello"), Helpers.Clamp(15, 0, 10) and Helpers.FormatDate(new DateTime(2024, 3, 15)).
Show example solution
Capitalize, Clamp and FormatDate.
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;
}
public static string FormatDate(DateTime date)
{
return date.ToString("yyyy-MM-dd");
}
}
class Program
{
static void Main()
{
Console.WriteLine(Helpers.Capitalize("hello"));
Console.WriteLine(Helpers.Clamp(15, 0, 10));
Console.WriteLine(Helpers.FormatDate(new DateTime(2024, 3, 15)));
}
}
Library complete
Your helper library is ready. The Helpers static class has three methods: Capitalize fixes text, Clamp keeps numbers in range, FormatDate formats dates. You can copy it into any project and use it.
The next group covers encapsulation: the public, private, protected and internal access modifiers, get/set properties, and how to protect your class's interior with init and required members.
Test yourself
-
Why is a helper library written as a static class?
- It compiles faster
- It is called without an instance, reducing repetition
- It uses less memory
- It allows inheritance
Show answer
It is called without an instance, reducing repetition — Correct. A static class needs no instance; methods are called directly.
-
Match each helper to its purpose
- Capitalize
- Text formatting
- Clamp
- Number range
- FormatDate
- Date format
- Helpers
- Static library
-
Complete the helper call
Console.WriteLine(Helpers.____("hello"));
Show answer
Console.WriteLine(Helpers.Capitalize("hello"));
Next lesson: Access modifiers