C# this

C# this keyword is used to refer to the current object. you can not use this keyword in a static method because the static method is called without refering to a specific object. Most of the time, i have used it to distingish between method paramter names and current class member variables as you see in the example code below.
//incorrect example code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{

   class Program
   {
     string ProName;
     int ProMonths;
     string ProMan;
     static void Main(string[] args)
     {
        setProInfo("ATM system",5,"Sok Dara");
        printProInfo();
        Console.Read();

     }
     static void setProInfo(string Proname, int ProMonths, string Proman)
     {
        this.ProName = ProName; //this keyword used in static method=>error
        this.ProMonths = ProMonths;
        this.ProMan = ProMan;
     }
     static void printProInfo()
     {
        Console.WriteLine("Project Name:{0}", ProName);
        Console.WriteLine("Project duration:{0} months", ProMonths);
        Console.WriteLine("Project Manager:{0}", ProMan);
     }
}
}
.............................................................................
//Correct example code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp_exercises
{

   class Program
   {
     string ProName;
     int ProMonths;
     string ProMan;
     static void Main(string[] args)
     {

        Program pr = new Program();
        pr.setProInfo("ATM system",5,"Sok Dara");
        pr.printProInfo();
        Console.Read();

     }
     void setProInfo(string Proname, int ProMonths, string Proman)
     {
        this.ProName = ProName;
        this.ProMonths = ProMonths;
        this.ProMan = ProMan;
     }
     void printProInfo()
     {
        Console.WriteLine("Project Name:{0}", ProName);
        Console.WriteLine("Project duration:{0} months", ProMonths);
        Console.WriteLine("Project Manager:{0}", ProMan);
     }
}
}

Posted by: Dara | post date: 01-25-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.