1

What is the difference between "Controls.Add(xyz)" and "this.Controls.Add(xyz)" in ASP.NET (C#)?

How/When does it matter if I am adding the same control onto a webpage but via two (different) aforementioned methods?

When one should be preferred over the other?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
YashG99
  • 529
  • 1
  • 10
  • 20
  • 2
    possible duplicate of [When do you use the "this" keyword?](http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword) – Magnus Dec 06 '11 at 18:50

6 Answers6

3

There is no difference; this refers to the current instance of the class you are in. Without specifying this, you will get the closest method within the current scope (which is this anyway).

Mark Avenius
  • 13,679
  • 6
  • 42
  • 50
2

In this case, there is little difference.

Using this makes your code a bit more explicit that it refers to a member of the class.

Use whatever you and your team agreed on.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

In your case, this represents the current instance of the class. Hence, unless you are dealing with extension methods, you should be good to use either way as it is a matter of semantics.

What is the difference between "Controls.Add(xyz)" and "this.Controls.Add(xyz)" in ASP.NET (C#)?
None.

How/When does it matter if I am adding the same control onto a webpage but via two (different) aforementioned methods?
It does not matter.

When one should be preferred over the other?
Using this is usually preferred as it is more explicit and helps code readability. But it is a matter of preference.

Reference: this (C# reference)

Kash
  • 8,799
  • 4
  • 29
  • 48
0

The difference is merely the text "this.". The two different statements perform the same tasks.

One should be preferred over the other based only on coding standards for your organization. (I like it best without the "this.")

John Fisher
  • 22,355
  • 2
  • 39
  • 64
0

The this pointer is explicitly pointing out the current instance.

Gjohn
  • 1,261
  • 1
  • 8
  • 12
0

No difference. It's a redundant qualifier but as Oded mentioned it's for code readability.

user1231231412
  • 1,659
  • 2
  • 26
  • 42