Extension methods are the static methods which are defined under the static classes. Since these methods are defined in static class then they are called without creating an instance of a class. Extension methods supports a reusability as they enable us to modify the existing type without creating a new derived type. When we are modifying an existing extension method then we don't need to re-compile it.
Features of Extension methods:
1. It must declare as a static method.
2. It must defined under the static class.
3. It must that it uses a "this" keyword in its first parameter.
4. After creating an extension method it must shown by the visual studio intellisense, When user press the dot after a type instance.
5. If we want to use a extension method then we need to import the namespace( where the extension method is defined ) in your source code.
See the below example
using System;
namespace ExtensionMethodAppliction
{
public static class ExtensionMethods
{
public static bool IsPalindrome(this String str)
{
for (int i = 0; i < str.Length / 2; i++)
if (str[i] != str[str.Length - i - 1])
{
return false;
}
return true;
}
}
}
using System;
namespace ExtensionMethodAppliction
{
class ExtentionMethodProgram
{
static void Main(string[] args)
{
string str = string.Empty;
Console.WriteLine("Enter the string to which you want to check :");
str = Console.ReadLine();
if(str.IsPalindrome())
{
Console.WriteLine("Entered string is palindrome ");
}
else
{
Console.WriteLine("Entered string is not palindrome");
}
Console.ReadKey();
}
}
}
In the above example we make a extension method IsPalindrome inside the static class. In this method we are passing a string type parameter so that it will called by the string type variable. This method return true if the given string is palindrome and false if not.
After creating a extension method we create a main method where we take string from the user and uses a extension method to check whether the string entered by the user is palindrome or not.
If the extension method returns true then user get the following message:
"Entered string is palindrome"
If the extension method returns false then user get the following message:
"Entered string is not palindrome"
0 Comment(s)