use of "this" keyword
hi guys can any one tell me the use of this keyword in C# language
i want to know what exactly the code
****string person(string fName, string lName)
{
this.fName=FirstName;
this.lName=LastName;
}****
means
and i want to know all the uses of this keyword
................thanks in advance
Bechir BejaouiPosted Feb 27, 2009, 7:56 PM
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int identifier { get; set; }
//The overloaded constructor
public Person(string FirstName,string LasName, int identifier)
{
//TO DO initialize the Person members within the constructor scope
}
}
OK, how to distiguish between the FirstName(member of the class instance) and FirstName(argument in the constructor), the world this enables the compiler distiguish between the two element inspite of the same name, same thing for the others I mean LastName and identifier so I write
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int identifier { get; set; }
//The overloaded constructor
public Person(string FirstName,string LasName, int identifier)
{
//Class member = Constructor arguement
this.FirstName = FirstName;
this.LastName = LastName;
this.identifier = identifier;
}
}
Ok you tell me I can change the arguement nomination firstName or fn or fname and avoid the conflict in the names I tell you the problem will persist you tell me how? I tell you
the class is used to derive several instances
Person me = new Person("Bejaoui", "Bechir", 1);
Person you = new Person("anveshreddy", "amaravadi", 2);
Person vijaya = new Person("Vijaya","Kadyiala",3);
Ok the problem is how the compiler can differenciate between the FirstName of me, the FirstName of you and the FirstName of Vijaya, is by using the this Keyword who serves as a pointer that point to the targeted FirstName among the rest of the FirstNames of the other instances
anveshreddy amaravadiPosted Feb 27, 2009, 5:29 PM
Vijaya KadiyalaPosted Feb 27, 2009, 3:42 PM
Hi
The this keyword refers to the current instance of the class. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
The following are common uses of this:
{
this.name = name;
this.alias = alias;
}
CalcTax(this);
Check out the below link:
http://msdn.microsoft.com/en-us/library/dk1507sz%28VS.71%29.aspx
Thanks -- Vijaya Kadiyala