0

In many of the samples I have seen that the programmer use

this.DataContext =x;

vs simply using DataContext = x; in the page code behind . I always use

DataContext = x;

in my code behind page to set the datacontext. The same is with other variables on the page, many use

this.Variable

to refer to it instead of simply using Variable . Whats the difference ?Or there is no difference and just programming practice .

Gaurav
  • 113
  • 6
  • I know what this keyword does. But I have seen this.DataContext at so many places .Why not use only DataContext , and as you have been so kind to tell me that this is a duplicate question , then please let me know which point from the answer to another question meets as the answer of this question – Gaurav Aug 06 '14 at 09:25

3 Answers3

0

When using objects, this.Variable will always point to a property of the current object. When you just use Variable, it will also point to the property unless there is a variable in the same scope with this name. In this case, this will point to the local variable.

It is always safer to use this.Variable, but not necessary.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • In case of DataContext , there is only going to be one DataContext , that of the page, then why use this.DataContext – Gaurav Aug 06 '14 at 09:17
  • The only reason I can give you is: just to be sure you have the right variable. You should ask the programmer why he does that. – Jerodev Aug 06 '14 at 09:46
0

In fact there is no difference, but best practice is to use this. this denote the current object

Thakur
  • 559
  • 6
  • 15
  • 1
    I would not agree, it is not a "best practice", it is rather a matter of choice for the programming team. – Ouarzy Aug 06 '14 at 09:05
0

"this" is used to access object of the current class. Which is the default behaviour if you do not precise the "this" keyword. So there is no difference and it is just programming practice.

You already have a full answer here: When do you use the "this" keyword?

Community
  • 1
  • 1
Ouarzy
  • 3,015
  • 1
  • 16
  • 19