Home of the AlmostImplementedException

Extension Methods for Strings

Extension methods are an easy way to add additional functions to an object.
Today i’ll show you 2 String-Extension methods and with that want to dig a little deeper into the matter. For Array-Extension-Methods have a look here.

An extension method is a static method which uses the this keyword on the first parameter and with that indicates to which object its belong. Extension methods are only allowed in static classes and its recommended to name this class like the Datatype its extending with the word “Extensions” at the end. For example “StringExtensions”.

Before we get to how it works, a special thing about the namespace of this class. Many times you read that you have to set the namespace to System to use the extension anywhere. But thats not true. Its the other way around. You have to use using with the namespace of the extension. In most classes “using System;” is there so you get the impression you can use it anywhere with the namespace System.

But now to the basic prinziple which is shown here:

If you now have a string and use the code completion, you will a new method called Revert. Its used like this:

As you may have noticed, we don’t give any parameters to this method although we definded one. The first parameter with the keyword this is filled with the object its called on. In this case the string “hello”. Every thing else is the same as in a normal method.
Oh and BTW the method don’t have to return a string. It can return anything you want.
But we want a string and here is a fast way to revert a string:

I wont go into details here, because its not important how it works (most will get it anyway). Just be assured its one of the fastest way to revert a string.

And now a little snippet for lazy people (like me :-):

As you can see, we now use a parameter. And the good old params-keyword is there (if you don’t know how it works, have a look). When you call this extension method you can replace playholders (for example {0}) with a value. Since we use the params-keyword and get an array of parameters you can replace as many placeholders as you want (in fact, you need to replace them all :-).

And here a little example of how to use the extensions methods (don’t forget to declare using with the namespace of the extension class)

For a little fun, just try to revert this one: “A man, a plan, a canal – Panama!”

Share :

, , , ,

Leave a Reply