Extension Method
An Extension Method is one kind of static method and having public access modifier so you can use it anywhere.
As code you will see is more similar like an instance method but there are two things which separate extension method and instance method.
- Static keyword
- this keyword in parameter.
In visual studio you can see Extension Method display with icon of DOWN ARROW.
Its better to use extension method as compare to instance method.
We will implement one method which check given value is EVENT value or not, which return the TRUE or FALSE.
Traditional Instance Method Class called MyInstanceMethodClass,
- public class MyInstanceMethodClass
- {
- public static bool IsEvenNumber(int CheckNumber)
- {
- bool result = false;
- result = (CheckNumber % 2 == 0);
- return result;
- }
- }
Extension Method Class called MyExtensionMethodClass,
- public static class MyExtensionMethodClass
- {
- public static bool IsEvenNumber(this int CheckNumber)
- {
- bool result = false;
- result = (CheckNumber % 2 == 0);
- return result;
- }
- }
Use of Instance Method Classes,
- int FirstNumber = 11;
- bool CheckFirstNumber = MyInstanceMethodClass.IsEvenNumber(FirstNumber);
Use of Extension Method Class,
- int SecondNumber = 12;
- bool CheckSecondNumber = SecondNumber.IsEvenNumber();
Difference between Instance Method and Extension Method
Instance Method | Extension Method |
1. Instance Method is classical method of calling any method. | 1. New concept which introduced in .NET version 3.0 C#. |
2. Instance method compulsory to call with class name.
Example: MyInstanceMethodClass.IsEvenNumber(FirstNumber);
| 2. Extension method no need to call with class name.
Example: SecondNumber.IsEvenNumber(); |
3. You can override Instance Method. | 3. You can not override extension method. |
We had implemented example in Console Application:
Program.cs code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ExtensionMethodConsoleApplication
- {
- class Program
- {
- static void Main(string[] args)
- {
- int FirstNumber = 11;
- bool CheckFirstNumber = MyInstanceMethodClass.IsEvenNumber(FirstNumber);
- Console.WriteLine("First Number is 11 IsEvenNumber Check Return Value " + CheckFirstNumber.ToString());
- Console.WriteLine();
- Console.WriteLine();
- int SecondNumber = 12;
- bool CheckSecondNumber = SecondNumber.IsEvenNumber();
- Console.WriteLine("Second Number is 12 IsEvenNumber Check Return Value " + CheckSecondNumber.ToString());
- Console.WriteLine();
- Console.ReadKey();
- }
- }
- public class MyInstanceMethodClass
- {
- public static bool IsEvenNumber(int CheckNumber)
- {
- bool result = false;
- result = (CheckNumber % 2 == 0);
- return result;
- }
- }
- public static class MyExtensionMethodClass
- {
- public static bool IsEvenNumber(this int CheckNumber)
- {
- bool result = false;
- result = (CheckNumber % 2 == 0);
- return result;
- }
- }
- }
Output: