Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKoray Erkan
1,235 PointsActually I didn't get the purpose of "this" generally. What does it refers to? Where do we use it effectively?
Actually I didn't get the purpose of "this" generally. What does it refers to? Where do we use it effectively?
4 Answers
Steven Parker
231,248 PointsThe keyword "this" generally refers to the current instance of a class.
Some examples of where it would be used can be found on this MSDN page.
In addition to the examples shown there, it is also used when defining extension methods, which have their own workshop here: C# Extension Methods.
Andy DeBruhl
11,651 Pointsthis refers to the current instance of an object. Taking the example code from above...
'''
class Program
{
string x;
public void input()
{
this.x = System.Console.ReadLine();
}
public static void Main()
{
Program pro = new Program();
pro.input();
Console.System.Write(pro.x);
}
}
''''
imagine when pro.Input is called that pro is where this is.....so pro.x inside of the input() method, this is replaced with pro which is the instance of the object. I have no idea if that helps but that is how i understand this.
Avan Sharma
7,652 Points"this" keyword is used to refer the object which is calling the function.
Note: All class member functions require an object for them to invoke unless they are static. The object which invokes the method will be referred using the keyword this.
class Program
{
string x;
public void input()
{
this.x = System.Console.ReadLine();
}
public static void Main()
{
Program pro = new Program();
pro.input();
Console.System.Write(pro.x);
}
}
Maddalena Menolascina
6,668 PointsI never fully understood its purpose, sorry but none of the above links helped me out... has anybody got a very simple example? Thank you very much