Engineering Gratitude πŸŽ‰πŸ‘

Engineering Gratitude πŸŽ‰πŸ‘

Create an Extension Method in C#?

Create an Extension Method in C#?

Subscribe to my newsletter and never miss my upcoming articles

Creating helper methods to reduce functions in your application that can also extend your desire method is called the extensions method.

Ever used Linq? Oh yes Linq provides sets of powerful extension methods ever. Creating extension methods in C# is very easy and fun if you know what you want to do with it.

So Whats the rule?

There are 2 main rules to get started with.

  1. You have to make your extension method Static.
  2. If you have to mark your data type as this in your method.

That's it. Let's start by creating one πŸ˜€ (I am showing you using a console app 😁😁).

Let's create some use cases to make an extension method.

Suppose we have a DateTime instance and you have a range of DateTime. Now our job is to find out if this DateTime instance that we have is in that range or not. The solution is pretty much small and straightforward, but we will build an extension method to reuse this in our application. Excited?

Lets code.

Suppose that is what we have right now.

image.png

And we want to verify that the selectedDate instance value is in that startDate and endDate range or not.

For better reusability, we want to separate all our extension methods to another folder/class.

So as per the rules are, in order to create an extension method, we have to mark the method as static and we have to mark the datatype as this that we want to pick up for our extension method.

image.png

So we created an extension method for that is called IsInBetween to determine that this is in between or not by giving us a boolean result. (you can return whatever you want)

image.png

public static bool IsInBetween(this DateTime datetime, DateTime startDate, DateTime endDate)
{
    return (startDate <= datetime && datetime <= endDate);
}

To sum up, this what the code looks like from the main function.

image.png

and the result is image.png

Happy Coding πŸ’―

Β 
Share this