C# Classes Explained - The this keyword
(Page 3 of 6 )
The "this" keyword gets you an access to an instance of the class, and you can use it with instance methods, instance constructors and instance properties. You can't use it with any static members; this makes sense because a static member works on the class itself, not on an instance of it. Use the "this" keyword followed by the (.) operator to get access to the class members on an instance object. Take a look at the following class:
using System;
namespace Company
{
public class Employee
{
public string FirstName;
public string LastName;
//the default constructor
public Employee()
{
this.FirstName = "Michael";
this.LastName = "Youssef";
}
}
}
In the Employee class's default constructor I used the "this" keyword to initialize the public fields FirstName and LastName, so this keyword pretends that you already have an instance of the Employee class.
Class members
Inside a C# class you have defined: fields, properties, methods, constructors, destructor, indexers, constants, events, delegates and operators. We will discuss Fields, Constants and Static Types in this article; we will have separate articles for each of the other Class members.
Next: Fields >>
More C# Articles
More By Michael Youssef