Extension Methods Are Easy with C#

dirkstrauss

Dirk Strauss

Posted on May 29, 2019

Extension Methods Are Easy with C#

I have said this many times before, I love using extension methods. They are probably the easiest methods to write and can power up your code like never before. If you what to find out more, read on.

LOOKING FOR SOMETHING ELSE? TRY THESE LINKS INSTEAD:

If you are a bit short on time, go and check out the video explainer on this topic.

This should get you up and running quickly with using extension methods in your own applications to enhance your code. If you want a little more, keep on reading.

Extension Methods Explained

If you want to add methods to existing types without having to recompile your code or without creating a new derived type, then extension methods are the way to go.

Extension methods are a special type of static method. These are then called on the type you are extending as if they were instance methods.

Extension Method displayed in IntelliSence

Have a look at the Microsoft document explaining extension methods in depth. Consider the following code listing:

public static bool ToInt(this string value)
{
    return int.TryParse(value, out var _);
}

This is a typical extension method that acts on a string type and checks to see if the string can be parsed to a valid Integer. Note that the TryParse uses an out var using a discards variable.

TIP: Introduced in C# 7.0, discards are temporary, dummy variables are intentionally unused. A discard is indicated by using the underscore (_) for its variable name.

Using Extension Methods

In order to use your extension method, you need to just call it as you would any method of that type. In our case, we are extending the String type. This is seen by the extension method signature in the previous code listing. It enables us to do the following:

var sValue = "15";
if (sValue.ToInt())
{
    // Do something
}

If the String variable can successfully be parsed to an Integer, then the extension method will return True. You can even modify the method to return the integer it parsed, instead of a Boolean. You would, of course, need to gracefully handle cases where the String value could not be parsed to an Integer.

Get the Source Code

If you want to grab a working example of the code, head on over to the following GitHub repo and clone the repo to your local machine.

dirkstrauss/ExtensionMethodsDemo

If you have any comments or suggestions, please feel free to put those in the comments section below.

The post Extension Methods Are Easy with C# appeared first on Programming and Tech Blog.

💖 💪 🙅 🚩
dirkstrauss
Dirk Strauss

Posted on May 29, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Extension Methods Are Easy with C#
programming Extension Methods Are Easy with C#

May 29, 2019