Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
1.62/5 (11 votes)
See more:
Hi
What is the meaning of the
C#
this
keyword in c# programming?
Posted
Updated 17-Mar-13 22:36pm
v2

It is a reference to the current object, the same as My in VB if you are coming from that background.
 
Share this answer
 
Comments
Marco Bertschi 18-Mar-13 4:38am    
Nice and clear, +5. It took me a bit to answer this because of the code sample I have added :~/

cheers,
Marco Bertschi
The "this" keyword refers to the class which you are currently writing code in it. I mainly use it to distinct between method parameters and class fields.

For example, let's assume you have the following class:

C#
public class Person
{
   string name = ""; //Field "name" in class Person
   
   //Constructor of the Person class, takes the name of the Person
   //as argument
   public Person (string name)
   {
       //Assign the value of the constructor argument "name" to the field "name"
       this.name = name; 
       //If you'd miss out the "this" here (name = name;) you would just assign the
       //constructor argument to itself and the field "name" of the
       //Person class would keep its value "".
   }
}


Hope I could make it clear to you.
You can find additional reference information at the according MSDN page[^].

cheers,
Marco Bertschi
 
Share this answer
 
Depending on where you r using it ,it has different meanings:-
1.Reference to current instance of class
2.Call another constructor from a constructor in same class.
3.Declare indexer
Below example covers above 3
C#
class abc
{
string x; //class member
public abc(string x)
{
//referring to current instance
this.x=x;//("this.x" refers to class member)
}
//calling another constructor
public abc():this("xyz")//calls abc(string x) before abc()
{
}
//declaring an indexer
public int this[int index]
{
get{return x[index];}
set{x[index]=value;}
}

4.also used in Extension methods

These are some meanings I know about "this" keyword.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Feb-14 18:34pm    
Correct, a 5.
—SA
Silent Guardian 21-Feb-14 8:52am    
ty :)
Kornfeld Eliyahu Peter 22-Jun-14 9:19am    
The 4 samples you listed here are the exact same. In all this means the current instance of the class (sometime referred as the context)...
hi!!
This keyword is used to refer to an instance of the class!!!!!!!!!!!

take a look of this link

http://msdn.microsoft.com/en-us/library/dk1507sz%28v=vs.71%29.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900