Author avatar

Dániel Szabó

This is It! Using the This Reference in C#

Dániel Szabó

  • Jan 9, 2020
  • 8 Min read
  • 594 Views
  • Jan 9, 2020
  • 8 Min read
  • 594 Views
Languages Frameworks and Tools
C#

Introduction

In order to understand the this keyword in C#, we need to take a journey into the OOP (Object-Oriented Programming) realm. We will discuss the basic principles of OOP and how the this keyword comes into the picture when we are working with classes and their instances.

Object-Oriented Programming

C# fully supports the Object-Oriented Paradigm, including the concepts of encapsulation, inheritance, and polymorphism.

Encapsulation: This term means that a group of related properties, methods, and members are treated as a single unit we refer to as an object.

Inheritance: This term refers to an ability to create a new class based on an existing class.

Polymorphism: This term refers to the idea that you can have multiple classes that are interchangeable, and each class can implement a method or property differently.

The terms class and object, or instance, are sometimes used interchangeably. However, we need to be careful as these terms refer to different things. In fact, classes describe a specific type of object or objects, while objects are usable instances of classes. We call the act of creating an object instantiation.

In everyday language, we could say that classes resemble animals, and objects resemble an actual dog, cat, or whatever type of animal comes to mind. Or, if you are familiar with ancient Greek philosophy, you could say that classes are like ideas, and objects are an embodiment of an idea. For example, there is the concept of love, and there are situations when you love someone.

Let's create a sample class and instantiate it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class SampleClass {
            public string SampleProperty { get; set; }
            public string SampleMethod(string message)
            {
                return $"This is the message: {message}";
            }
        }
        static void Main(String[] args)
        {
            SampleClass test = new SampleClass();
            test.SampleProperty = "Pluralsight";
            Console.WriteLine($"This is the value of the SampleProperty: {test.SampleProperty}");
            Console.WriteLine($"This is the message from the SampleMethod: {test.SampleMethod("This is cool")}");
            Console.Read();
        }
    }
}
csharp

The output looks like this.

1
2
This is the value of the SampleProperty: Pluralsight
This is the message from the SampleMethod: This is the message: This is cool
bash

This example is important for multiple reasons. It demonstrated the auto-property and how you can implement properties and methods in your classes and call them.

Note how we set the SampleProperty with the test.SampleProperty line, which actually works because we implemented the {get;set;} in the property. We also called the SampleMethod, which returned a string with the specified message. This was a very basic demo, so let's complicate things a bit further.

Let's demonstrate our inheritance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class A
        {
            public string whatstring = "Default value";
            public void WhatMethod()
            {
                Console.WriteLine($"Coming from class A, what string: {whatstring}!");
            }
        }
        public class B : A
        {
            public void setstring (string newvalue)
            {
                whatstring = newvalue;
            }
        }
        static void Main(String[] args)
        {
            B c = new B();
            Console.WriteLine($"Default value of whatstring: {c.whatstring} coming from class A!");
            c.setstring("New Value");
            Console.WriteLine($"Calling inherited method of WhatMethod: c.setstring() with result of: {c.whatstring}");
            Console.Read();
        }
    }
}
csharp

The result looks like this.

1
2
Default value of whatstring: Default value coming from class A!
Calling inherited method of WhatMethod: c.setstring() with result of: New Value
bash

Note how we inherited the property of whatstring from A base class, along with the function called WhatMethod. We only called the setstring method implemented in the B class to modify the inherited property. Then the output concludes our modifications and shows the very definition of inheritance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class PolyMomo
        {
            public string PropertyOne = "DefaultOne";
            public string PropertyTwo = "DefaultTwo";

            public void Properties(string one, string two)
            {
                PropertyOne = one;
                PropertyTwo = two;
            }

            public void Properties(string onlyFirst)
            {
                PropertyOne = onlyFirst;
            }
        }
        static void Main(String[] args)
        {
            PolyMomo Demo = new PolyMomo();
            Console.WriteLine($"Property values before change, PropertyOne: {Demo.PropertyOne}, PropertyTwo: {Demo.PropertyTwo}");
            Demo.Properties("first", "second");
            Console.WriteLine($"Both properties were changed PropertyOne: {Demo.PropertyOne}, and PropertyTwo: {Demo.PropertyTwo}");
            PolyMomo DemoTwo = new PolyMomo();
            Console.WriteLine($"Property value before change, PropertyOne: {Demo.PropertyOne}!");
            DemoTwo.Properties("OnlyFirst");
            Console.WriteLine($"Only first property was changed to: {DemoTwo.PropertyOne}");
            Console.Read();
        }
    }
}
csharp

This gives us the following output:

1
2
3
4
Property values before change, PropertyOne: DefaultOne, PropertyTwo: DefaultTwo
Both properties were changed PropertyOne: first, and PropertyTwo: second
Property value before change, PropertyOne: first!
Only first property was changed to: OnlyFirst
bash

This demonstration is perfect to prove the polymorphic nature of our class. We have defined the Properties method with two signatures. The first one changes both of the properties we have in our class. The second one is changes only the value of the PropertyOne in our class.

There is a catch, however. If we would like to change only the second property, called PropertyTwo, we are unable to define the following function.

1
2
3
4
public void Properties(string onlySecond)
	{
		PropertyTwo = onlySecond;
	}
csharp

This gives us the error:

CS0121 The call is ambiguous between the following methods or properties: 'ThisRef.PolyMomo.Properties(string)' and 'ThisRef.PolyMomo.Properties(string)' Pluralsight

This means that the same type of parameter signature cannot be present in our class.

The This Reference

The this keyword is used to reference the current instance of a class, or an object itself, if you will. It is also used to differentiate between method parameters and class fields if they both have the same name. If you want to go extremes, you can also use the keyword to call another constructor from a constructor in the same class.

Our demonstration looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class Thissser
        {
            public string whatever;
            public Thissser(string whatever) {
                this.whatever = whatever;
                Console.WriteLine($"The constructor was called with argument :: {whatever}");
            }
        }
        static void Main(String[] args)
        {
            Thissser Demo = new Thissser("Well this is it!");
            Console.Read();
        }
    }
}
csharp

This returns the following output.

1
The constructor was called with argument :: Well this is it!
bash

Conclusion

In this guide, you've learned about the this keyword. I wrapped it in the OOP package as much as possible, going through the necessary fields that allow you to gain better understanding of the function of this keyword. We closed our guide with a demonstration code that shows how you can apply your newly gained knowledge and incorporate it into your applications. I hope this has been informative to you and you found what you were looking for.

5