-4

Does it refer to the object the handler it is defined in or the object than handle belongs to:

example:

class foo  
{
 Object a;
 public foo()
 {
  a.handle += function;    
 }

 void function()
 {    
   this;<--What does this "this" refer to foo or object a?
 }    
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
SamFisher83
  • 3,937
  • 9
  • 39
  • 52
  • `this` always refers to the current class instance when used inside a class. – cbr Jul 07 '15 at 18:34
  • 1
    `The this keyword refers to the current instance of the class` From [this C#](https://msdn.microsoft.com/en-us/library/dk1507sz.aspx) – Habib Jul 07 '15 at 18:35
  • 1
    I can only assume that you are coming from JavaScript background, see [this in JavaScript vs C#](http://coding.abel.nu/2013/02/this-in-javascript-vs-c/) – Habib Jul 07 '15 at 18:37
  • @NikhilAgrawal I disagree with the duplicate. It doesn't answer OP's question at all. No doubt it's a duplicate of an existing question, but not of this one. – user247702 Jul 07 '15 at 18:38
  • `this` is not Javascript – leppie Jul 07 '15 at 18:41

2 Answers2

2

this refers to foo. In c# the this pointer always refers to the instance of the class containing the method

Dustin Hodges
  • 4,110
  • 3
  • 26
  • 41
0

In an event handler, you can cast the "Sender" object to the type you know the object to be, and then you can tell for sure which object you are handling the event for.

Dwedit
  • 618
  • 5
  • 11