Extension methods are an easy way to "add" functionality to existing types without having to create derived types, recompile, or otherwise modify the original type. Extension methods are a static method, but they are called as if they were methods on the target type. Using C#, there is no apparent difference between calling an extension method and the methods that are actually part of the defined type.
Here is an example extension method. This method will extend the object string to break apart camel cased names and return a human readable name. This can be very useful for populating drop down lists with all values of an Enumeration and other such activities. First, we create the static method as follows.
public static string SplitCamelCase(this String input) { return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim(); }This simply create a method (SplitCamelCase) and adds it to the methods available to any String variable in namepace scope with this class.
Then, this method can be called in the same format as any other method on the type String.
static void Main(string[] args) { String testValue = "ThisIsACamelCasedSentence"; Console.WriteLine(testValue.SplitCamelCase()); }
These methods are quite simple to create and yet are a very powerful replacement for utility classes. They can be used on native types as well as complex types.
Hi there, I enjoy reading all of your post.
ReplyDeleteI wanted to write a little comment to support you.
my web site :: hultquist jewellery wholesale