this keyword in C#

  • It works like an object for the current class.
  • The this keyword refers to the current instance of the class. 
  • When instance variables and local variables are same then this keyword is used to access instance variables.
  • In general, local variables overrides instance variables and instance variables are no more visible inside the method. So this can be used to refer instance variables to make visible inside method.
  • The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
  • For example,
  • public class Emp
            {
                private int _Sal = 5000;
                public void increment(int _Sal)
                {
                    MessageBox.Show("Local variable value");
                    MessageBox.Show(_Sal.ToString());//_Sal=3000
                    MessageBox.Show("Instance variable value");
                    MessageBox.Show(this._Sal.ToString());//this._Sal=5000
                    this._Sal = this._Sal + _Sal;
                }//increment
                public void print()
                {
                    MessageBox.Show("Incremented Salary"); 
                    MessageBox.Show(_Sal.ToString());
                }//print
            }//Emp
            private void button1_Click(object sender, EventArgs e)
            {
                Emp em = new Emp();
                em.increment(3000);
                em.print();
            }
        }

0 comments :

Post a Comment

> Related Posts with Thumbnails
 

Copyright © 2012. GS dot net - All Rights Reserved - Design by BTDesigner - Proudly powered by Blogger