Extension methods are a powerful feature in C# that allow you to add new methods to existing types without modifying their source code. This is particularly useful for enhancing a type provided by a third party or when you want to add utility methods to all aspects of an existing object type.
To create an extension method, you define a static method in a static class, and the first parameter of the method must use the `this` keyword followed by the type you want to extend. Once defined, these methods can be called as if they were instance methods on the extended type.
Here's an example of how to create and use an extension method:
public static class StringExtensions
{
public static int WordCount(this string str)
{
return string.IsNullOrWhiteSpace(str) ? 0 : str.Split(' ').Length;
}
}
// Usage
string example = "Hello world";
int count = example.WordCount();
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?