Extension methods
It is sometimes useful to add functionality to a type without changing the implementation, creating a derived type, or recompiling code in general. We can do that by creating methods in helper classes. Let's say we want to have a function that reverses the content of a string because System.String
does not have one. Such a function can be implemented as follows:
static class StringExtensions { public static string Reverse(string s) { var charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } }
This can be invoked as follows:
var text = "demo"; var rev = StringExtensions.Reverse(text);
The C# language allows us to define this function in a way that enables us to call it as if it was an actual member...