Articles → CSHARP → Extension Method In C#
Extension Method In C#
Purpose
Scenario
- Create a custom class and add a method IsEvenNumber in it
- Create an extension method
Create A Custom Class
public class UsefulFunctions {
public bool IsEvenNumber(int num) {…
}
}
Create Extension Method
- Create a static class
- Inside the class create a static method
- Pass an argument of any data type of which you want to write the extension method prefixed by this keyword
public static class ExtensionMethodsClass {
public static bool IsEvenNumber(this int num) {
bool status = false;
if (num % 2 == 0) {
status = true;
}
return status;
}
}
int x = 3;
MessageBox.Show(x.IsEvenNumber().ToString());