Home » .Net

'this' reference in C#.Net with Example

Learn: 'this' in C#.Net: What is 'this' reference in C#.Net, explain the concept of 'this' in C#.Net with an Example?

'this' in C#.Net

In C#.Net ‘this’ is a reference of current object, which is accessible within the class only.

To access an element of class by referencing current object of it, we use this keyword, remember following points:

  1. this keyword is used.
  2. this cannot be used with the static member functions.

C# Example of 'this' reference

Consider the program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

    class Sample
    {
        private int a;
        private int b;

        public Sample()
        {
            a = 0;
            b = 0;
        }

        public void setValues(int a,int b)
        {
            this.a = a;
            this.b = b;
        }
        public void printValues()
        {
            Console.WriteLine("A: " + a + " B: " + b);
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Sample S;

            S = new Sample();

            S.setValues(10, 20);
            S.printValues();

            Console.WriteLine();

        }
    }
}

Output

A: 10 B: 20

In above program within setValues() method, this is used to differentiate between data member of class and local variable of method. Because this is a reference of current class object it can be used as data member.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.