The 'This' Reference Variable - Learn Object-Oriented Programming in C#
The 'This' Reference Variable - Learn Object-Oriented Programming in C#
Object-oriented Programming
in C#
13% completed
Search Module
Introduction to Object-
Oriented Programming
in C#
Access Modifiers
Fields
Methods
Accessing a Field
Got any feedback? Get in touch with us.
We can use the this when we have a method argument which has the same name as
a field. It’s always a good convention for the beginners to use the this keyword in
their class implementation when initializing or accessing the fields. This will help us
avoid any confusion or errors.
1 class VendingMachine {
2
3 private int moneyCollected = 70;
4
5 // A simple print function
6 public void PrintMoney(int moneyCollected){
7 Console.WriteLine("Money Collected using this variable: " + this.moneyCollected);
8 Console.WriteLine("Money Collected without using this variable: " + moneyCollected);
9 }
10
11 }
12
13 class Demo {
14
15 public static void Main(string[] args) {
16 //passing the parameters
17 var vendingMachine = new VendingMachine(); // Object created with parameterized const
18 vendingMachine.PrintMoney(-10);
19 }
20
21 }
In the above code, we have used the this keyword on line 7. The purpose of using
Got any feedback? Get in touch with us.
this here is to differentiate between the arguments being passed to the method and
the fields of the class. For example, this.moneyCollected means we are referring to
the field of the class while simply using moneyCollected means that we are referring
to the argument being passed to the method.
At this point, we know all about the fields and methods of a class. In the next lesson,
we will discover an efficient way of declaring fields and how to manipulate these
fields using specific methods.