Extension methods allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type.
Key Points:
1: Extension Class must be static
2: Extension Method must be static
3: 1st Param in extension method must contains type which are geting extended
Example:
class Program
{
static void Main(string[] args)
{
//Default String
String str = "My Name is XYZ";
//LINQ Query to get count of vowels (use of Extension method)
var queryChar = from ch in str.ToUpper()
where ch.IsVowel()
select ch;
//Display result
Console.WriteLine("Calling Char Extension Method:");
Console.WriteLine("String \"{0}\" contains {1} Vowels", str,
queryChar.Count());
queryChar.Count());
Console.WriteLine();
//Count Words in string (use of Extension method)
int countWords = str.CountWords();
Console.WriteLine("Calling String Extension Method:");
Console.WriteLine("String \"{0}\" contains {1} Words", str,
countWords);
countWords);
Console.WriteLine();
//Get Factorial from given integer (use of Extension method)
Console.WriteLine("Enter an integer to get factorial");
int i = int.Parse(Console.ReadLine());
Console.WriteLine("Calling Int Extension Method:");
Console.WriteLine("Factorial of {0} is: {1}", i, i.GetFactorial());
Console.ReadLine();
}
}
/*Creating Extension Method*/
static class Exten
{
public static bool IsVowel(this char ch)
{
return "AEIOU".Contains(ch);
}
public static int CountWords(this string str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
public static Int64 GetFactorial(this int x)
{
if (x <= 1) return 1;
if (x == 2) return 2;
else
return x * GetFactorial(x - 1);
}
}
Output:
Calling Char Extension Method:
Calling Char Extension Method:
String "My Name is XYZ" contains 3 Vowels
Calling String Extension Method:
String "My Name is XYZ" contains 4 Words
Enter an integer to get factorial
8
Calling Int Extension Method:
Factorial of 8 is: 40320
No comments:
Post a Comment