Extension methods allow us to add methods to existing classes without changing the class’ source code, nor by inheriting from the class. Extension methods are more relevant when wanting to add a method to a class from which one cannot inherit, such as sealed classes.
Just note, you cannot use extension methods with a static class as extension methods require an instance variable for an object in order to be utilised.
Let us look at an example, here we will add an extension method to the string class, which is a sealed class (i.e. you cannot inherit from this class).
class Program { static void Main(string[] args) { string sentence= “This is something a person would say.”; var robotSentence = sentence.ToRobot(); Console.WriteLine(robotSentence); } } public static class StringExtensions { public static string ToRobot(this string str) { if(String.IsNullOrEmpty(str)) return str; var words = str.Split(‘ ‘); var robotStr = String.Empty; foreach(var word in words) { if(word.Length > 4) { robotStr+=“BEEP “; } else { robotStr+=“BOOP ”; } } return robotStr.Trim(); } }
Also note that extension methods must be non-generic static methods defined in a static class.