Extension methods with a c# example
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Emily FosterRank #3,495 · 415 reputationPosted May 12, 2025, 11:33 PM EDT
Absolutely! Extension methods in C# allow you to add new methods to existing classes without modifying the original class or creating a new derived class. This can be quite handy when you want to extend the functionality of classes that you can't modify directly, such as built-in .NET framework classes.
Here's a simple example to illustrate how extension methods work in C#:
using System; public static class StringExtensions { public static bool IsPalindrome(this string input) { string reverse = ""; for (int i = input.Length - 1; i >= 0; i--) { reverse += input[i]; } return input == reverse; } } class Program { static void Main() { string word = "radar"; bool isPalindrome = word.IsPalindrome(); Console.WriteLine($"{word} is a palindrome: {isPalindrome}"); } }In this example, we define an extension method `IsPalindrome` for the `string` class. The `IsPalindrome` method checks if a given string is a palindrome (reads the same backward as forward). We then call this extension method on a string variable in the `Main` method.
Extension methods can be quite powerful for adding custom functionality to existing classes or frameworks without altering their original source code. They provide flexibility and versatility in C# programming.