Use of "this"

Hi,

Can anyone please tell me how this is used in C#?

“this” refers to the current instance of the class/struct. For example if you have a variable in your class and you want to use the same name for a parameter you can prefix the current instance variable with “this”.

public class SomeClass
{
   private float someVar = 1.0f; // this is always equal to "this.someVar"

   public void DoSomething(float someVar)
   {
      this.someVar += someVar;
   }
}

A lot of people also prefix their fields with an underscore(private float _someVar) which I believe is a relic from C/C++. Using “this” is the proper styling in C#.

It is also used as the first parameter of extension methods to specify the calling object instance.

public static class SomeClassExtension
{
   public static void DoSomethingElse(this SomeClass myInstance, float myVariable)
   {
      myVariable *= 25.0f;
      myInstance.DoSomething(myVariable);
   }
}
3 Likes

this refers to the current instance, so you can use it in the case @jimroberts pointed out, to distinguish between a member variable and a other var of the same name.

The other useful thing, is if you need your class to be able to pass reference to its self to a other class or function.

2 Likes

Thanks for the feedback.

I was wondering whether this could be used when you attach a code to a game object to reference itself. For example, if there’s a code attached to a Cube, rather than going: Public GameObject Cube

And dragging the Cube from the hierarchy to the public slot in the code attached to itself in the inspector

or
putting

cube = GameObject.Find ("Cube");

in the start function,

is there anyway to do something like

Cube = this.gameObject

instead?

this is really if you need a reference to yourself most important it becomes when you need to call a method wich requires the object you are calling it from. like methodthatrequiresmyobjectreference(this);
also in cases where method parameters have the same name as one of your member variables it makes sense
to prefix your own member with this.
all other cases make no sense and only lengthen your code.

1 Like

As long as your script inherits from Component (all MonoBehaviours do this), then yes, you could use this.gameObject, but in that case the this keyword is superfluous, you can do just Cube = gameObject

3 Likes

Thanks for your help.