Method problem with 'this' keyword

I want to create a method using this Transform as parameter :

 void Test (this Transform tr) {
    // do whatever with tr, such as modifying its position and rotation        
}

so that I can use it like this :

myTransform.Test();

But that doesn’t work.

Code completion won’t propose the Test() method, and if I type it manually, I obtain an error saying that Transform has no definition for Test().

Of course I could get rid of this and call the Test() method this way :

Test(myTransform);

But it is less elegant, and above all I’d like to better understand the usage of the this keyword.

To make an Extension of Transform, you will need to make a static class to keep them in:

 public static class TransformExtensions {
     public static void Test(this Transform tr) {
         // do whatever with tr, such as modifying its position and rotation
      }
 }

Then, you can use the following:

myTransform.Test();

And the usage of “this” in this case is to make an extension. This calls from Transform instead of passing in a parameter.

Other places you use “this” is when you are referring to the class instance that the code is in.

this.someClassProperty 

would call the current class’s property, even if an overriding variable (has the same name) exists.