Extension Methods

Extension Methods allow you to "add" methods to an existing type without modifying or inheriting from it. They are declared as static methods with the this keyword before their first parameter and can be called like instance (non-static) methods. For example:

// Extension methods must be in a static class.
public static class ExtensionMethods
{
    public static Color WithAlpha(this Color color, float alpha)
    {
        return new Color(color.r, color.g, color.b, alpha);
    }
}

// In some other method:

var color = Color.red.WithAlpha(0.5f);
// Color.red is  (r=1, g=0, b=0, a=1)
// color will be (r=1, g=0, b=0, a=0.5f)

// You can also still use it as a regular static method:
var color = ExtensionMethods.WithAlpha(Color.red, color);