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...