what is extension method
Loading
what is extension method
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ajay BansodePosted Jul 24, 2025, 3:36 PM
What is an Extension Method in C#?
An extension method is a static method that allows you to "add" new methods to existing types (like
string,int, custom classes, etc.) without modifying their source code or using inheritance.Key Points
Declared in a static class.
The first parameter uses the this keyword before the type you want to extend.
Can be called as if it were a regular method on the object.
Example: Extension Method on
string1. Define Extension Method
public static class StringExtensions
{
public static bool IsNumeric(this string input)
{
return int.TryParse(input, out _);
}
}
2. Use it like a regular method:
string value = "12345";
bool result = value.IsNumeric(); // Output: true
Even though
stringhas noIsNumeric()method, now you can call it as if it does!Another Example:
intExtensionpublic static class IntExtensions
{
public static bool IsEven(this int number)
{
return number % 2 == 0;
}
}
// Usage:
int num = 10;
bool isEven = num.IsEven(); // Output: true
Why Use Extension Methods?