0

Possible Duplicates:
Is this keyword optional when accessing members in C#?
When do you use the “this” keyword?

class Program
    {
        public class Demo
        {
            int age;
            string name;

            public Demo(int age, string name)
            {

                // 'THIS' KEYWORD IS ADDED IN THESE TWO LINES THEN ONLY IT WORKS
                age = age;
                name = name;
             }

            public void Show()
            {
                Console.WriteLine("Your age is :" + age.ToString());
                Console.WriteLine("Your name is : " + name);
            }
        }

        static void Main(string[] args)
        {
            int SENDage;
            string SENDname;

            Console.WriteLine("Enter your age : " );
            SENDage=Int32.Parse(Console.ReadLine());

            Console.WriteLine("Enter your name : ");
            SENDname=Console.ReadLine();

            Demo obj = new Demo(SENDage, SENDname);

            obj.Show();
            Console.ReadLine();
        }
    }

I found this reason , but can anyone please explain it to me?

Local data members age , name have precedence over instance members.

I am not able to understand it.

Community
  • 1
  • 1
sqlchild
  • 8,754
  • 28
  • 105
  • 167
  • 1
    it should work without `this` in your above example – naveen May 21 '11 at 11:11
  • are you sure? i tried this exact code in: 2.0, 3.0, 3.5 and 4.0 and each time it worked absolutely fine. what are you using? – peteisace May 21 '11 at 11:11
  • The code as-is works fine, there is no need to use `this` here at all. – H H May 21 '11 at 11:11
  • 1
    If you're actually asking why the `this` keyword is part of the C# language in the first place, well, you need a way to express a reference to the current object, e.g. in order to pass it to other methods, or return it from your own. – Frédéric Hamidi May 21 '11 at 11:13

3 Answers3

4

In this situation the this keyword would not be required. It is only necessary when the following declaration is changed:

int a;
string n;

Into

int age;
string name;

To use the class variable instead of the argument to the constructor you would then have to assign it with this:

        public Demo(int age, string name){
            this.age = age;
            this.name = name;
         }
Mr47
  • 2,655
  • 1
  • 19
  • 25
  • ok , i have changed the code, now tell me the reason explanation please – sqlchild May 21 '11 at 11:30
  • which one are the local members? – sqlchild May 21 '11 at 11:30
  • 1
    the 'local members' would be the arguments that are passed to your function (in this case the constructor). – Mr47 May 21 '11 at 11:31
  • then , why does it show blank value? when constructor is called, then it receives the values or not? Because Local Members have precedence, so is the value entered by the user received or not by these variables? – sqlchild May 21 '11 at 11:39
  • 1
    Yes; when you do not use the `this` keyword, using `age` or `name` will access the variables that were passed as arguments; thus they will be filled with the values provided to the constructor. – Mr47 May 21 '11 at 11:41
  • @Mr47-so sir, then why this value printed is blank? – sqlchild May 21 '11 at 11:46
  • 1
    The variable before the assignment operator must be the global variable (class-level field), so you must add `this`. The way you wrote it will assign the value of the argument right back to the same variable (the argument) and not to the global variable (class level field). – Mr47 May 21 '11 at 11:48
  • ok, so if i use THIS, then what does it do? – sqlchild May 21 '11 at 11:50
  • does it tells the compiler , to point to the GLOBAL VARIABLES, but according to the definition of THIS, "it points to the current instance", and the current instance variables here are the local ones? – sqlchild May 21 '11 at 11:52
  • 1
    `this` is a reference to the instance of the class you are currently executing code in. So `this.name` refers to the field of the object; while `name` refers to the argument to your constructor. `this` thus allows you to indicate that you require the variable `name` within the scope of `this` as opposed to the standard local scope (the function in which you are executing code; your constructor). – Mr47 May 21 '11 at 11:53
  • so you mean , it refers to the IMPLICITLY created instance, not to the explicitly created one--->Demo obj = new Demo(age,name); -----not to "obj"? – sqlchild May 21 '11 at 11:56
  • 1
    `this` does refer to obj, but from inside the object itself. Your local variables (the arguments to your constructor) are destroyed the moment you leave the constructor. So you put your values in the class fields by using `this`, so you can fetch the content of these fields in your `show` method. – Mr47 May 21 '11 at 12:01
  • if in a new Form1.cs i put this line : Form2 form2 = new Form2(this); then which instance will be passed to the constructor of Form2? – sqlchild May 21 '11 at 12:04
  • also, sir, if we dont create any instance , then also the default constructor is called? in this case, is an implicit instance created or not? I simply created a new Windows Application with a new Form1, and directly debugged it, and it successfully displayed the form1. but how? i din't create any instance, then how did it call the default constructor? – sqlchild May 21 '11 at 12:08
  • 1
    That would be the instance of form1 that is passed on to form2. If you don't provide arguments, you call the default constructor. If you call the default constructor, you will still have the `this` keyword available to you in all forms, allowing you access to the object (not function!) currently executing code. – Mr47 May 21 '11 at 12:11
  • but sir, i din't create any instance of FORM1 , explicitly , then also , it executes ? why so? – sqlchild May 21 '11 at 12:15
  • 1
    Your FORM1 is created by the main execution loop of your application. Even if you did not create an instance, one will be created by your execution loop. Otherwise nothing would happen when your program is started. – Mr47 May 21 '11 at 12:17
  • 1
    you mean in Program.cs it is created? – sqlchild May 21 '11 at 12:27
  • That is what I mean yes. – Mr47 May 21 '11 at 12:32
2

This code runs just fine for me when I copy-paste it into a console application.

What do you mean by "this" keyword is required? doesn't it compile? what version of Visual Studio are you using?

Alternatively, Is this the whole code or just a demo you made portraying the problem? From the error message it seems like you have "age" and "name" defined somewhere else, perhaps "a" and "n" were previously called "age" and "name"?

ewino
  • 185
  • 1
  • 9
  • He means to say "What is the use of this keyword in the constructor" ?, It's just that he hasn't framed his question properly. – Searock May 21 '11 at 14:45
1

In your code the parameter name age and class member age are of same name.

public class Demo
{
     int age;
     string name;

     public Demo(int age, string name)
     {
          age = age;
          name = name;
     }

     .....
}

When your code executes the constructor, it first searches for the local variable and then searches for the class variables. Since it gets the age and name both as local variable it reassigns the value back to it self.

Now if you use this keyword for assigning values, this keyword refers to the current object and hence assigns the value to the object.

public class Demo
{
     int age;
     string name;

     public Demo(int age, string name)
     {
          this.age = age;
          this.name = name;
     }

     .....
}
Searock
  • 6,278
  • 11
  • 62
  • 98