3

Possible Duplicate:
When do you use the “this” keyword?

If I have the following example:

public class MyClass {

private void MyMethod1()
{
    ...
}

private void MyMethod2()
{
    this.MyMethod1();
    ...
}

}

In the "MyMethod2" is there a difference in use "this.MyMethod1()" or just "MyMethod1()"? Performance, security, good practice, or whatever? I ask this, because normally I don't use "this" to call methods in the same class, but I get code developed by other people that use it... maybe I'm wrong... or not!

Sorry if looks like a silly question, but I'm "curious" after all. Thank you!

Community
  • 1
  • 1
Kira
  • 608
  • 3
  • 10
  • 22
  • What about Myclass::MyMethod1(); – adhanlon Aug 19 '10 at 20:57
  • 1
    http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword http://stackoverflow.com/questions/1845573/c-using-the-this-keyword-in-this-situation http://stackoverflow.com/questions/843288/c-when-to-use-this-keyword-closed – dtb Aug 19 '10 at 20:58

3 Answers3

3

In that specific example there is no difference - it will compile to identical bytecode.

It only makes a difference if there is a local variable or parameter with the same name as the method you want to call, in which case you need to write this to refer to the member and not the local variable.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

Not performance, they will compile to the same IL.

The thing with the this keyword is that it you don't have local variables with the same naming as the class members.

private void MyMethod2()
{
    Action MyMethod1 = MyMethod2;
    MyMethod1(); // recursive call to MyMethod2

    this.MyMethod1(); // call to real MyMethod1
}

Other than that some people like it, some does not. Follow the code standard in your team.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
0

There is no difference from an execution standpoint. As you imply, some people use this, some don't.

Use the standard you've decided is correct, unless you are overridden by company standards.

automatic
  • 2,727
  • 3
  • 34
  • 31