C Sharp/this Operator

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Home

Basics
Home
introduction
Overview
Statements
Data Types
Variables
Operators
Flow Control
Variables II
Functions
C# - Classes and Objects I

Dates and Times
Conversions

Advanced
Classes II
Inheritance
GUI
Namespaces
Exceptions
Threads
ADO.NET
Generics

[edit] The C# this Operator

The this operator points to a class field member. In some situations it may be necessary to use the name of a field member. The only way to distinguish between the two is to use the this operator for the field member. Take a look at the following code:


using System;
class Program
{
    public class test
    {
        public int MyAge;
        public int MyMethod(int MyAge)
        {
            this.MyAge = MyAge;
            ++this.MyAge;
            return this.MyAge;
        }
    }
    static void Main()
    {
        test ClassObject = new test();
        Console.WriteLine(ClassObject.MyMethod(18));
        Console.Read();
    }
}

Output:

19

As you can see the local variable in the MyMethod method is named MyAge. The field variable is named MyAge also. So how does the compiler suppose to distinguish between the two. Well, by using the this operator point to the field variable in the class.

If the this operator was not used the local variable in the method would be used.