What are extension methods in C#? Provide an example of when and how you would use one.

In C#, extension methods are a powerful feature that allows you to add new functionality to existing types (like classes, structs, or interfaces) without modifying their source code. This is particularly useful when you want to enhance the functionality of types that you cannot directly change, such as built-in types or third-party libraries.

Extension methods are static methods defined in a static class. They are recognized as “extensions” to a type when their first parameter is preceded by the this keyword. The type specified after this indicates which type the method extends.

When to Use Extension Method

  1. To add utility functions to types you don’t own (e.g., string or DateTime).
  2. To keep your code organized by grouping related functionality.
  3. To enhance the readability of your code by calling methods directly on an object.

YouTube

How to Use Extension Methods

Here’s an example:

Suppose you frequently need to count the number of words in a string. You can create an extension method for string:

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        if (string.IsNullOrWhiteSpace(str)) return 0;
        return str.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

// Usage:
string sentence = "C# extension methods are awesome!";
int wordCount = sentence.WordCount(); // Calls the extension method
Console.WriteLine(wordCount); // Output: 5

Benefits

  • You can call WordCount as if it were a method of string.
  • It keeps your main logic clean and improves reusability. Extension methods allow you to extend types in a non-intrusive, modular way, enhancing your code’s flexibility and maintainability.
extension methods

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top