Language of Integrated Query - Part One

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,

  1. public class ScheduledTask  
  2. {  
  3.     public Task someTask;  
  4.     public ScheduledTask(TimeSpan duration, TimeSpan run)  
  5.     {  
  6.         //run the task after every duration until run hours  
  7.     }  
  8. }   
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
  1. public class CreateScheduedTask  
  2. {  
  3.     public CreateScheduedTask1()  
  4.     {  
  5.         var scheduledTask = new ScheduledTask(new TimeSpan(0, 0, 2, 0), new TimeSpan(0, 1, 0, 0));  
  6.     }  
  7. }  
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,
  1. public class CreateScheduedTask  
  2. {  
  3.     public CreateScheduedTask2()  
  4.     {  
  5.         var scheduledTask = new ScheduledTask(runAfter: 2. Minutes(), runUntil: 1. Hour());  
  6.     }  
  7. }  
  8. public static class StringExt  
  9. {  
  10.     public static TimeSpan Minutes(this int minutes)  
  11.     {  
  12.         return new TimeSpan(0, 0, (minutes), 0);  
  13.     }  
  14.     public static TimeSpan Hour(this int hour)  
  15.     {  
  16.         return new TimeSpan(0, hour, 0, 0);  
  17.     }  
  18. }  
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.
Ebook Download
View all
Learn
View all