views:

557

answers:

11

How does the system know what to use when 'this' keyword is used?

Recently, I was asked this question in an interview. Having never thought about this, I replied back saying that the system will know the current context in which the flow of control is and decide the object to be used instead of this. The interviewer didn't look pleased and he moved on to the next question.

Can anyone tell me what did the interviewer may have wanted to ask and what would be the answer? (I think this can interpreted in different ways and hence keeping this as wiki unless someone point out not to..)

+9  A: 

this is a hidden parameter in all methods of an object and contains a copy of the instance pointer.

Aaron Digulla
+1  A: 

At run time "this" will resolve to the pointer to the current object, therefore "the system" will be able to call a respective method on that object.

Developer Art
'..."this" will resolve to the pointer to the current object'. How does it know about current object?
Sandbox
I suppose the method stack will receive an extra parameter with an address of the object in which context a method is being executed.
Developer Art
A: 

in c the this pointer is an invisible pointer argument to your class.

So in essence the first argument to a class method is the pointer to the class itself. You reference it by using this.

Toad
'this' is not a keyword in C.
William Pursell
nor does C have classes
Muad'Dib
yeah yeah..I meant c++ of course. ;^)
Toad
+1  A: 

I would have answered "It is a reference to the instance of the current class."

Dan

Daniel Elliott
That's not an answer to the question at all.
Matt Ball
+12  A: 

The this keyword is a pointer to the current object. All non-static member functions of a class have access to a this pointer.

The pointer to the current object is normally made available by the compiler in a non-static member function by using a register, usually ECX. So when you write this in a non-static member function the compiler will translate that call into loading the address from ECX.

Check this simple example:

A t;
t.Test();
004114DE  lea         ecx,[t] 
004114E1  call        std::operator > (41125Dh) 

Before calling the non-static member function Test() the compiler loads the register ECX with [t] (the address of variable t - will be this inside Test method).

004114DE  lea         ecx,[t]

And inside the function it can use ecx to obtain the address for the current object instance.

smink
As it is C#, the more simple CIL would be appropriate.
Dykam
thanks for that killer answer.
iterationx
+2  A: 

Consider this class

class A {
private:
    int data;
public:
    void SetData(int arg) {
        this->data = arg;
    }
}

and this code that calls SetData():

A objA;
objA.SetData(1);

When the above code is compiled, the compiler emits something equivalent to this for the member function:

void SetData(A* this, int arg) {
     this->data = arg;
}

And the calling code is converted to something like this:

A objA;
SetData(&objA, 1);

What this means is that upon compilation:

  1. Member functions are converted to simple, global functions.

  2. The class instance to which member functions "belong" is simply passed as the first argument to them (or rather its address is passed).

So in conclusion, what you refer to as this pointer in your code simply ends being the the first argument to the function. This is how the "system knows" which object to access through the "this" pointer.

The above example is of C++. If you for a moment forget about the CLR and the JITting and all that, what happens in C# is conceptually the same thing.

Frederick
A: 

Shematicaly compiler converts such code:

pObject->someMethod(A,B,C)

Into such code if 'someMethod' is not virtual:

someMethod(pObject,A,B,C)

Or into such code if 'someMethod' is virtual:

(*pObject->vtable[someMethodIndex]) (pObject, A,B,C)

And everywhere you place 'this' keyword first parameter is used instead of it;

Of course compiler may optimize/simplify by removing first argument and use some CPU register (normally esx) to store object's address.

inazaruk
+1  A: 
Joel Martinez
A: 

My answer would have been "Who cares? It knows. If I ever need to find out in more detail I'll Google it."

You obviously know what the effect of using "this" would be, which surely is the important thing. For 99% of programming tasks I would have thought that the detail of how it is resolved internally is trivia.

Alan B
That attitude would not be likely to win you the interviewer's approval.
Kevin Panko
Wow...are you sure you're on the right site?
Crazy Joe Malloy
Well, my answer IF I DIDN'T KNOW THE ACTUAL ANSWER would be the above!
Alan B
A: 

The "this" operator will point to the current object. An example where the presence of a "this" operator will make a difference is this:

public class MyClass
{
    int value;
    public void Test(int value)
    {
        MessageBox.Show(value); // Will show the parameter to the function
        MessageBox.Show(this.value); // Will show the field in the object
    }
}

Note that the "this" operator will not change what virtual function will be called if it is overridden in a child class

public class MyClass
{
    public virtual void Test() {}
    public void CallTest()
    {
        this.Test();
    }
}
public class MyClass2 : MyClass
{
    public override void Test() {}
}

If you execute the following code

MyClass c = new MyClass2();
c.CallTest();

will still call the MyClass2.Test() and not MyClass.Test()

So the "this" operator simply tells you, that you are accessing something declared at class level.

Pete
What do you mean by 'that the "this" operator will not change what virtual function will be called if it is overridden in a child class'...what do you mean by this(pun not intended)?
Sandbox
+13  A: 

Though the answers which point out that the "this" reference is essentially passed as a magic "hidden parameter" to the call are essentially correct, the full story is actually quite a bit more complicated in C# than one might think at first glance.

Reference types are straightforward; the referenced object is checked for null and then conceptually passed as an unnamed, non-variable parameter called "this". The story is complicated by value types.

Remember, value types are, by definition, passed by value -- that is, passed by making a copy of the data. Hence their name. But clearly mutable value types -- which are pure evil and should be avoided -- cannot be passed by value as the "this", because if you called a mutator, the "this" in the mutator method would be mutating the copy, not the original!

Therefore, in a value type's method call, "this" is not the value of the receiver, it is an alias to the variable representing the storage location of the receiver. We implement this by passing "this" as the managed address of the receiver, not the value of the receiver.

Now we can raise another difficulty. What if the variable storing the value being mutated is a read-only variable? Now what do we do? If you're curious, read my article on the subject and see if you can correctly answer the puzzle presented:

http://blogs.msdn.com/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx

Eric Lippert
thanks you for your words of wisdom O Great One....Now please go forth and implement new langague features that will blow our collective minds
Anthony
Thank you for the answer and great link.
Sandbox