Q:

\'this\' reference in C#.Net with Example

0

'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.
  3.  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Explain Cascaded Method call in C# with an Example... >>
<< C# program to demonstrate the class and object cre...