Extension Methods
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 39 of 70.
Extension methods let you add new methods to existing types without modifying their source code or creating derived classes. They appear as if they're native methods of the type, making your code more readable and intuitive.
To create an extension method, define a static method in a static class, with the first parameter preceded by the this keyword:
public static class StringExtensions
{
public static int WordCount(this string str)
{
return str.Split(' ').Length;
}
}Now you can call this method directly on any string:
string sentence = "Hello World Today";
int count = sentence.WordCount(); // 3The this string str parameter tells the compiler this method extends the string type. When you call sentence.WordCount(), the compiler translates it to StringExtensions.WordCount(sentence) behind the scenes.
Extension methods can also accept additional parameters:
public static bool IsLongerThan(this string str, int length)
{
return str.Length > length;
}
// Usage
bool result = "Hello".IsLongerThan(3); // trueThis technique is used extensively in LINQ, where methods like Where() and Select() are extension methods on IEnumerable. Extension methods are powerful for adding utility functions to types you don't control, keeping your code clean and expressive.
Challenge
EasyLet's build a set of useful extension methods for integers that add convenient functionality you'd expect to have built-in. You'll create a static class containing extension methods that can be called directly on any integer, making your code more expressive and readable.
You'll organize your code across two files:
IntExtensions.cs: Create a static class calledIntExtensionsin theUtilitiesnamespace. This class will contain extension methods that enhance theinttype:IsEven()- returnstrueif the number is even,falseotherwiseSquare()- returns the number multiplied by itselfIsInRange(int min, int max)- returnstrueif the number is between min and max (inclusive),falseotherwise
thiskeyword to specify which type you're extending.Program.cs: In your main file, read an integer from input and demonstrate all three extension methods. Call each method directly on the integer as if it were a built-in method, then print the results.
You will receive three inputs:
- A number to test (integer)
- Minimum value for range check (integer)
- Maximum value for range check (integer)
Print the output in this format:
Is {number} even? {True/False}
Square of {number}: {result}
Is {number} in range [{min}-{max}]? {True/False}For example, if the inputs are 7, 5, and 10, the output should be:
Is 7 even? False
Square of 7: 49
Is 7 in range [5-10]? TrueNotice how naturally you can write number.IsEven() and number.Square() - the extension methods feel like they've always been part of the integer type!
Cheat sheet
Extension methods allow you to add new methods to existing types without modifying their source code. They must be defined as static methods in a static class, with the first parameter preceded by the this keyword.
Basic extension method syntax:
public static class StringExtensions
{
public static int WordCount(this string str)
{
return str.Split(' ').Length;
}
}Usage:
string sentence = "Hello World Today";
int count = sentence.WordCount(); // 3The this keyword before the first parameter indicates which type is being extended. The compiler translates sentence.WordCount() to StringExtensions.WordCount(sentence).
Extension methods with additional parameters:
public static bool IsLongerThan(this string str, int length)
{
return str.Length > length;
}
bool result = "Hello".IsLongerThan(3); // trueTry it yourself
using System;
using Utilities;
class Program
{
public static void Main(string[] args)
{
// Read inputs
int number = Convert.ToInt32(Console.ReadLine());
int min = Convert.ToInt32(Console.ReadLine());
int max = Convert.ToInt32(Console.ReadLine());
// TODO: Use the extension methods on 'number' and print the results
// Call number.IsEven(), number.Square(), and number.IsInRange(min, max)
// Print in the format:
// Is {number} even? {True/False}
// Square of {number}: {result}
// Is {number} in range [{min}-{max}]? {True/False}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator