Extension methods let you add new actions to existing types like strings or numbers without changing their original code.
Extension methods for built-in types in C Sharp (C#)
public static class ClassName { public static ReturnType MethodName(this Type parameter, other parameters...) { // method body } }
The this keyword before the first parameter tells C# this is an extension method.
Extension methods must be inside a static class and be static themselves.
IsAllLetters method to strings to check if all characters are letters.public static class StringExtensions { public static bool IsAllLetters(this string str) { foreach (char c in str) if (!char.IsLetter(c)) return false; return true; } }
IsEven method to integers to check if a number is even.public static class IntExtensions { public static bool IsEven(this int number) { return number % 2 == 0; } }
This program adds a new method to strings to check if they contain only letters. It then tests two words and prints the results.
using System; public static class StringExtensions { public static bool IsAllLetters(this string str) { foreach (char c in str) if (!char.IsLetter(c)) return false; return true; } } public class Program { public static void Main() { string word1 = "Hello"; string word2 = "Hello123"; Console.WriteLine($"{word1} is all letters: {word1.IsAllLetters()}"); Console.WriteLine($"{word2} is all letters: {word2.IsAllLetters()}"); } }
Extension methods look like normal methods when you use them, but they are static methods behind the scenes.
You can add extension methods to any type, including built-in types like string and int.
Extension methods cannot access private members of the type they extend.
Extension methods add new actions to existing types without changing them.
They must be static methods inside static classes, with this before the first parameter.
They help keep code clean and let you add useful features to built-in types.