C# Extension Methods


Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. For example, there a situations on your projects when you can’t modify a class directly, and this can be for different reasons, but you still want to add functionality to that class. Here’s when Extension Methods joins the party.

Let’s use a real case scenario. Imagine you want to check when an object with certain tag collides with another.

This is what you’ll normaly do in Unity, isn’t it?

This looks totally normal, right? But what happens if we want to check several tags at the same time and not only the *Player* tag?

In this way, our OnTriggerMethod will check for every single tag we specify through the inspector with the _tags variable.


If we want to implement the same behaviour in other classes we’ll have to create the same FOR loop everytime we want to check several tags.

So, let’s use extension methods.

Create a custom class and call it however you want. In my case I’ll use “GameObjectExtensions”.

There are some rules you gotta follow once creating c# extension methods:

1 — They should be places in a Static Class.

2 — Extension methods should always be statics, same as classes.

3 — The first parameter on a extension methods is always the class you want to override, in this case it is GameObject.

Note: Do not forget to use System.Linq namespace to be able to use the “Contains” method.

Now, we’ve just overrided the CompareTag method from the GameObject class.

If we return back to our OnTriggerEnter2D method you should notice that now you just have to specify the array to make this work.

And this is how you use extension methods. They are really good when you want to maintain a clean project without having to break your head.