Thursday, July 10, 2025

Extension Methods in C#

I was explaining extension methods in C# to somebody and realized it was a good topic for a blog post, so here we are.

Extension methods are a way to enhance (or extend) an existing object. If you've done any significant coding with C# I can virtually guarantee you've already used extension methods that were built-in to the framework. Things like " banana ".Trim(), which removes leading and trailing whitespace from the string. But you can also create your own extension methods and it's actually pretty easy to do.

First you need to identify what you're trying to extend. For example, if you always want to safely convert a string to an integer and return -1 when the string is not an integer, would you be extending strings or ints? The answer is strings.
 
I actually wrote a separate post with some examples of string extensions that I use pretty frequently. Basically, we're extending (hence the name) the framework's built-in capabilities so we can manipulate an object (type) more easily. Extension methods are a great way to avoid littering your application with helper methods like "GetTrimmedString(string toTrim)". But you want to be aware of unnecessarily polluting your code base with extension methods that are only used in one place.

No comments:

Post a Comment