Extension Method
An extension method is a static method of a static class which can be invoked using the instance method syntax.Extension methods are used to add new behaviors to an existing type without modifying it.
In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
if you don't understand it, don't worry. below example will give you more clarification.
class Proram
{
public static void Main()
{
Console.Write("Enter value between 5 to 10 :- ");
int i = Convert.ToInt32(Console.ReadLine());
//check if given value is in given range or not
string isInRange= i.InRange();//Extension Method called
Console.WriteLine(isInRange);
Console.ReadLine();
}
}
public static class ExtensionMethod
{
public static string InRange(this int val)//This keyword is used with first parameter
{
if (val > 5 && val < 10)
{
return "Given value is in Range";
}
else
{
return "Given value is not in range";
}
}
}
Output:
Enter value between 5 to 10 :- 6
Given value is in Range
In above you can see that we have create extension method InRange in ExtensionMethod class.
InRange method has parameter int val with this keyword. this keyword should be used with first parameter of method.
if you have any doubts on that please add your question in comment box.
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.