Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "this" mean in a static method declaration?

I've seen some code that uses the keyword this in the function parameter declaration. For example:

public static Object SomeMethod( this Object blah, bool blahblah)

What does the word this mean in that context?

like image 454
Yochai Timmer Avatar asked Feb 22 '11 08:02

Yochai Timmer


1 Answers

It means SomeMethod() is an extension method to the Object class.

After defining it you can call this method on any Object instances (despite it being declared static), like so:

object o = new Object();
bool someBool = true;

// Some other code...

object p = o.SomeMethod(someBool);

The this Object parameter refers to the object you call it on, and is not actually found in the parameter list.

The reason why it's declared static while you call it like an instance method is because the compiler translates that to a real static call in the IL. That goes deep down though, so I shan't elaborate, but it also means you can call it as if it were any static method:

object o = new Object();
bool someBool = true;

// ...

object p = ObjectExtensions.SomeMethod(o, someBool);
like image 125
BoltClock Avatar answered Sep 20 '22 15:09

BoltClock