C#

Top 5 Small but Must have Extension Methods2 min read

In this post I want to cover some very basic and small extension methods which are very useful for any developer. All below mentioned extension method are not doing any complex operation. Rather they are just performing very simple task which you generally encounter a lots of times

1. IsNull




This is probably most commonly used expression. A lots of places in out code we check to null references. We usually add the obj == null or obj != null check to do this. Here is the IsNull extension method

Using the you can avoid the lazy null check. Example:

2. FormatString

We often use string.Format to format the string like

The alternative way to do this is using below extension method

Now the above example can be re-written as

3. RaiseEvent

How you generally raise you events? I guess something like below

Here for each event you need to check the null reference before you raise it and also you create a new method so that you don’t have to add this check each place from where you are raising the event even if there is no special logic in the function. Here it the set of extension method to raise the events that matches the signature of EventHandler or EventHalder<TEventArgs>:

Now this is how to raise the above event

4. Match

This extension method is for pattern matching in any string using Regex. This is how you generally use it

And here is the extension method to do this simply

After this look at the code below. It became much simpler than the traditional approach:

5. ToInt

This method has three flavors, for Int16, Int32 and Int64. This can be easily used while doing string to int conversion. Here are the methods:

 

About the author

admin

Leave a Comment