Home »
.Net »
C# Programs
'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:
- this keyword is used.
- 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.
C# Basic Programs »