Lnaguage of integrated Query – Part 1

So this is first part of multiple blog series in which i will discuss the power of LINQ

To begin with i will discuss Extensions method and how we can use them and why we need them. But before we start have a look at the following code

public class ScheduledTask
{
	public Task someTask;
 
	public ScheduledTask(TimeSpan duration, TimeSpan run)
	{
		//run the task after every duration until run hours
	}
}

Now in the above code if you read it you can say that this class with create a scheduled task which will run after every ‘duration’ minutes and its going to run for the next ‘run’ hour. We may get some idea from here though its bad naming convention but when we will 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 suppor engineer to read this. So to make it more readiable we use Extensions Methods. You can only use Extension methods with premitive 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 dont use extensions where they are not needed. Every extension method should reside in the same namespace as the class where it is being used.