To begin with, I will discuss the extensions method and how we can use it and why we need it. But before we start have a look at the following code,
- public class ScheduledTask
- {
- public Task someTask;
- public ScheduledTask(TimeSpan duration, TimeSpan run)
- {
-
- }
- }
Now in the above code if you read it you can say that this class will create a scheduled task which will run after every ‘duration’ minute and it's going to run for the next ‘run’ hour. We may get some idea from here though that it's a bad naming convention, because when we use it we will have no clue of what we did when we see the code again. So when I call this I will write this
- public class CreateScheduedTask
- {
- public CreateScheduedTask1()
- {
- var scheduledTask = new ScheduledTask(new TimeSpan(0, 0, 2, 0), new TimeSpan(0, 1, 0, 0));
- }
- }
It will be really hard for the support engineer to read this. So to make it more readable we use Extensions Methods. You can only use Extension Methods with primitive type so after using extension method this class will look like this,
- public class CreateScheduedTask
- {
- public CreateScheduedTask2()
- {
- var scheduledTask = new ScheduledTask(runAfter: 2. Minutes(), runUntil: 1. Hour());
- }
- }
- public static class StringExt
- {
- public static TimeSpan Minutes(this int minutes)
- {
- return new TimeSpan(0, 0, (minutes), 0);
- }
- public static TimeSpan Hour(this int hour)
- {
- return new TimeSpan(0, hour, 0, 0);
- }
- }
Now don't use extensions where they are not needed. Every extension method should reside in the same namespace as the class where it is being used.