Extension Methods

· 1 min read

Extension Methods are a feature that adding new methods to an existing class, which class is non-generic but static class. Similar to the extension concept in Swift.

Features of Extension methods:

  • Create a static class to include all the Extension methods we want to create
  • Extension methods are static
  • First parameter is this
  • We can only add methods but can't override methods

Example of Extension methods in Unity

using UnityEngine;
using System.Collections;


public static class ExtensionMethods
{
    //Notice that the first
    //parameter has the 'this' keyword followed by a Transform
    //variable. This variable denotes which class the extension
    //method becomes a part of.
    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

To use above extension methods:

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        transform.ResetTransformation();
    }
}